Reputation: 586
I retrieve data from an API and want to add new properties(comments:[], likes:''
, etc.) each of the map. What I tried is that modifying data on UI side, and it didn't effect Firestore side. Even I modify the data on Firestore side by creating new collection it works until I refresh the app. Can you please show me the correct way how to modify and store the data?
const newsFromApiRef = firestore().collection('topHeadlines');
//Adding data to firestore
const newsOnFirebase = async () => {
await getTopHeadlines('us')
.then((data) => {
newsFromApiRef
.doc('testDocUID')
.set(data)
.then(() => {
console.log('Data added succesfully');
})
.catch((error) => {
console.log(error);
});
})
.catch((error) => {
console.log(error);
});
};
//Getting data from firestore, and added new properties
const getFromFirebase = async () => {
await newsOnFirebase();
var data;
await newsFromApiRef
.doc('testDocUID')
.get()
.then((querySnapshot) => {
const newData = [];
querySnapshot.data().articles.forEach((list) => {
if (list?.comments) {
newData.push({ ...list });
} else {
newData.push({
...list,
comments: [],
});
}
});
data = {
articles: [...newData],
status: querySnapshot.data().status,
totalResults: querySnapshot.data().totalResults,
};
})
.catch((error) => {
console.log(error);
});
return data;
};
Upvotes: 0
Views: 65
Reputation: 83068
If you want to get a document's data from Firestore and add new properties to this document, you need to first query for the document (with the get()
method), as you do, and then write back to Firestore, either with the update()
or set()
methods (which you don't do).
Since you are using async/await
, you can do along the following lines:
const snap = await newsFromApiRef.doc('testDocUID').get();
const docData = snap.data();
const newData = [];
docData.articles.forEach((list) => {
if (list?.comments) {
newData.push({ ...list });
} else {
newData.push({
...list,
comments: [],
});
}
});
const data = {
articles: [...newData],
status: docData.status,
totalResults: docData.totalResults,
};
await newsFromApiRef.doc('testDocUID').update(data);
Note that since you read one document, you are actually getting a DocumentSnapshot
, and not a QuerySnapshot
, hence the renaming in my anwser.
Upvotes: 1