Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier.
done by using add method
// Add a new document with a generated id
const res = await database.'collectionName'.add({//obj goes here
name: 'Tokyo',
country: 'Japan'
});
console.log('Added document with ID: ', res.id);
Update a document in firebase.firestore() i.e. database
done by update method
using onSnapshot : this gives current content of database collection, we use this real time property of onSnapshot to set our state
therefore what happens is that when ever their is a state change, component and its children get re-rendered
In our project we use onSnapshot in Feed.js (to setUserData) & Posts.js (to setPosts)
Examples below:
const unsub = database.posts.orderBy('createdAt', 'desc').onSnapshot(querySnapshot => {
postsArr = [];//emptying postsArr as whenever new vid is put this method is called and
//querysnapshot provides info of all vids, therefore, if we dont empty postsArr it will lead to double entry of vids in our array
querySnapshot.forEach((doc) => {
console.log(doc.data(), +" " + doc.id);
let data = { ...doc.data(), postId: doc.id }
postsArr.push(data)
})
setPosts(postsArr);
})
const unsub = database.users.doc(currentUser.uid).onSnapshot((doc) => {
// You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot
immediately with the current contents of the single document.
// Then, each time the contents change, another call updates the document snapshot.
console.log(doc.data());
setUserData(doc.data())
//any change in users.doc by header or uploadvideo will be noticed by onSnapshot and it will run statements in useEffect
//also will re-render any children of feed component
})
**using get method** : this is a simple fetch request with no real time monitoring/listener feature, can be used in child/deeper components as we don't want a listener there as child is re-rendered multiple time due to change in parent
let eachComment=await database.comments.doc(commentId).get()
commentsArray.push(eachComment.data());