Got these two methods. I have a class which calls the method getFamily before this.family is assigned since onSnapshot has not finished loading. How can i restructure this so a call to getFamily will wait for onsnapshot to finish? Is it possible to use promises?
getFamily() {
return this.family;
}
setFamilyID(familyID) {
this.familyID = familyID;
this.db.collection("families").doc(this.familyID).onSnapshot((familyDoc) => {
console.log("family updated");
this.family = familyDoc;
});
}
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.
Firebase offers two cloud-based, client-accessible database solutions that support realtime data syncing: Cloud Firestore is Firebase's newest database for mobile app development. It builds on the successes of the Realtime Database with a new, more intuitive data model.
The firestore. collection(). onSnapshot() function returns a unsubscribe function. Just call it and you should be guchi.
If you need realtime updates, wrap the onSnapshot
in a Promise
. You'll need to keep a handle on the return value of onSnapshot
so you can detach when the component is destroyed. Also, make sure to only call resolve
once.
getFamily() {
return this.family;
}
setFamilyID(familyID) {
this.familyID = familyID;
return new Promise((resolve, reject) => {
var resolveOnce = (doc) => {
resolveOnce = () => void;
resolve(doc);
};
this.detachFamilyIDWatcher = this.db
.collection("families").doc(this.familyID)
.onSnapshot((familyDoc) => {
console.log("family updated");
this.family = familyDoc;
resolveOnce(familyDoc);
}, reject);
});
}
If you only need to load the data once, then just use get
instead of onSnapshot
. get
returns a Promise
and doesn't require detaching.
getFamily() {
return this.family;
}
setFamilyID(familyID) {
this.familyID = familyID;
return this.db
.collection("families").doc(this.familyID)
.get().then((familyDoc) => {
console.log("family updated");
this.family = familyDoc;
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With