Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait for firebase to load onsnapshot

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;
    });
}
like image 915
Rob Avatar asked Aug 10 '18 20:08

Rob


People also ask

What is onSnapshot in firebase?

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.

Is firestore real time?

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.

How do I turn off onSnapshot firestore?

The firestore. collection(). onSnapshot() function returns a unsubscribe function. Just call it and you should be guchi.


1 Answers

Realtime

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);
  });
}

Just Once

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;
    });
}
like image 175
Bryan Massoth Avatar answered Sep 23 '22 22:09

Bryan Massoth