Firebase how to update child value in javasscript - javascript

i want to to update child value depending on categoryId. I tried following this tutorial Firebase DB - How to update particular value of child in Firebase Database. It’s work, but it’s not storing in the same ref. It’s store in another ref.
https://i.stack.imgur.com/SaqjD.png
firebase.database().ref('usuario')
.on('value',event =>{
event.forEach(user =>{
user.child('eventos').forEach(evento =>{
if (evento.val().categoryId === payload.id){
//Here is where i try to update the childe value, in my case category
let ref = firebase.database().ref('usuario/'+user.key+'/'+evento.key+'/'+evento.val().category)
.set(payload.name)
console.log(ref)
}
})
});
});

2 problems:
1.You forgot to add "\eventos" on you child path.
2.dont use .set(), because it will delete all the other data.
Instead of .set() use .update().
Try this code:
firebase.database().ref('usuario')
.on('value',event =>{
event.forEach(user =>{
user.child('eventos').forEach(evento =>{
if (evento.val().categoryId === payload.id){
//Here is where i try to update the childe value, in my case category
let ref = firebase.database().ref('usuario/'+user.key+'/eventos/'+evento.key+'/'+evento.val().category)
.update(payload.name)
console.log(ref)
}
})
});
});
Let me know if it still dont work

Related

Add item to state after post in API get the id

I have a component where I can click to "add a study". This click triggers two things :
1 - post in my API
2 - adding to my state to re-render the component.
So, it works BUT when I record the data in my state, I have not the ID of the study and I need it after. So is it possible to do something to have this ID ? Or I am forced to re-call my API to get all my studies ?
My code in my component :
const addStudy = {
name : this.newStudy.nameStudy,
status: "In prepa",
project: "api/projects/" + this.newStudy.currentIdProject,
compareStudy: false,
basic: true
}
axios
.post('http://127.0.0.1:8000/api/studies', addStudy)
.then(this.$store.commit("addStudie", {projet : this.newStudy.currentIdProject, study :addStudy}))
And in my store :
addStudie(state, {projet, study}) {
const theProject = state.listProjects.projects.find(p => p.id === projet)
theProject.studies.push(study)
}
Thanks a lot
i seems there is an issue with the request. In my opinion, it should change to
axios
.post('http://127.0.0.1:8000/api/studies', addStudy)
.then((result)=>{
this.$store.commit("addStudie", {projet : this.newStudy.currentIdProject, study :result
})
})
if you have any problem place let me know
You can save your ID in the localStorage that saves key value string data on the client side (browser)
addStudie(state , id) {
// do somthing with state then save it into localStorage
localStorage.setItem('myID', id);
}
And a store getter that returns the id from localStorage
theId(state) {
const savedID = localStorage.getItem("myID")
return savedID
}
if(theId()){
// do something with your ID
}
else{
// ID is not saved in the localStorage yet , call the API
getDataFromAPI()
}

Firestore retrieve single document by field value and update

I'm trying to retrieve a single document by a field value and then update a field inside it.
When I do .where("uberId", "==",'1234567'), I am getting all the docs with field uberId that matches 1234567.
I know for sure there is only one such document. However, I don't want to use uberId as the document's ID, otherwise I could easily search for the document by ID. Is there another way to search for a single document by a field ID?
So far, reading the docs, I could see this:
const collectionRef = this.db.collection("bars");
const multipleDocumentsSnapshot = await collectionRef.where("uberId", "==",'1234567').get();
Then I suppose I could do const documentSnapshot = documentsSnapshot.docs[0] to get the only existing document ref.
But then I want to update the document with this:
documentSnapshot.set({
happy: true
}, { merge: true })
I'm getting an error Property 'set' does not exist on type 'QueryDocumentSnapshot<DocumentData>'
While you may know for a fact there's only one document with the given uberId value, there is no way for the API to know that. So the API returns the same type for any query: a QuerySnapshot. You will need to loop over the results in that snapshot to get your document. Even when there's only one document, you'll need that loop:
const querySnapshot = await collectionRef.where("uberId", "==",'1234567').get();
querySnapshot.forEach((doc) => {
doc.ref.set(({
happy: true
}, { merge: true })
});
What's missing in your code is the .ref: you can't update a DocumentSnapshot/QueryDocumentSnapshot as it's just a local copy of the data from the database. So you need to call ref on it to get the reference to that document in the database.
async function getUserByEmail(email) {
// Make the initial query
const query = await db.collection('users').where('email', '==', email).get();
if (!query.empty) {
const snapshot = query.docs[0];
const data = snapshot.data();
} else {
// not found
}
}

Async issue with State in React Native

I'm trying to build a simple app that lets the user type a name of a movie in a search bar, and get a list of all the movies related to that name (from an external public API).
I have a problem with the actual state updating.
If a user will type "Star", the list will show just movies with "Sta". So if the user would like to see the actual list of "Star" movies, he'd need to type "Star " (with an extra char to update the previous state).
In other words, the search query is one char behind the State.
How should it be written in React Native?
state = {
query: "",
data: []
};
searchUpdate = e => {
let query = this.state.query;
this.setState({ query: e }, () => {
if (query.length > 2) {
this.searchQuery(query.toLowerCase());
}
});
};
searchQuery = async query => {
try {
const get = await fetch(`${API.URL}/?s=${query}&${API.KEY}`);
const get2 = await get.json();
const data = get2.Search; // .Search is to get the actual array from the json
this.setState({ data });
} catch (err) {
console.log(err);
}
};
You don't have to rely on state for the query, just get the value from the event in the change handler
searchUpdate = e => {
if(e.target.value.length > 2) {
this.searchQuery(e.target.value)
}
};
You could keep state updated as well if you need to in order to maintain the value of the input correctly, but you don't need it for the search.
However, to answer what you're problem is, you are getting the value of state.query from the previous state. The first line of your searchUpdate function is getting the value of your query from the current state, which doesn't yet contain the updated value that triggered the searchUpdate function.
I don't prefer to send api call every change of letters. You should send API just when user stop typing and this can achieved by debounce function from lodash
debounce-lodash
this is the best practise and best for user and server instead of sending 10 requests in long phases
the next thing You get the value from previous state you should do API call after changing state as
const changeStateQuery = query => {
this.setState({query}, () => {
//call api call after already changing state
})
}

Retrieving data on firebase having child key uid (javascript)

I am struggling how to retrieve data from firebase having a child key, such as uid.
here is the structure of my firebase.
Currently I am making an admin panel which can read the order placed by each user and render it through flatlist in react native, but it seems that I can't access their order because every time the user places an order it is stored on their unique User.id
I don't know how to make a reference to the User.id child like firebase.database().ref(orders/${AllUserId}/products)
You can use forEach loop to fetch ids and can get values as so
firebase.database().ref('order').on('value', (snapshot) => {
snapshot.forEach((child) => {
uid = child.key; // gives uid1
child.forEach((snap) =>{
var id = snap.key; // first iteration gives uid2
firebase.database().ref('order/'+uid+'/'+id).on('value', (snapchild) => {
snapchild.forEach((snapshotchild) =>{
console.log(snapshotchild.val());
});
});
});
});
});
This could be more insightful.

how can i save object in mobille storage using react native

I am building an application in which I want to save user data. and user able to see that data later. I am using AsyncStorage.. i want to store multiple values in one key. I used AsyncStorage.setItem.. here is my code..
var obj ={
name : "sabih",
color : "blue"
}
AsyncStorage.setItem('myKey', JSON.stringify(obj))
.then(() => {
console.log('data saved')
})
but when i get data with AsyncStorage.getItem. it gives me like this
{"name":"sabih" , "color" : "blue"}
Code here
AsyncStorage.getItem("myKey").then((data) => {
var userData = JSON.parse(data)
console.log(userData, 'Get Values')
}).done();
How can i set name's and color's value in state. or how can i render these values in my react native application..
Thanks in advance.
and please attach a snap of solution if possible..
Create a function inside your file and call that function passing your asyncstrorage value as parameter as below :-
_renderDetail=(item)=>{
this.setState({user:item});
}
and inside your asyncStorage code edit as :-
AsyncStorage.getItem("myKey").then((data) => {
var userData = JSON.parse(data);
console.log(userData, 'Get Values');
this._renderDetail(userData);
}).done();
and then you can use this state variables inside your render function as :-
<Text>{this.state.user.name}</Text>
<Text>{this.state.user.color}</Text>

Categories