7

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;
    });
}
1
  • i believe you want async/await Aug 10, 2018 at 21:00

1 Answer 1

15

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;
    });
}
2
  • 1
    Returning promise was a good idea however can you explain why you declare resolveOnce variable-function instead of just calling the newly created Promise resolve? Sep 22, 2020 at 10:47
  • @TarvoMäesepp Did you figure out why they did that?
    – H.b
    Jul 6, 2022 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.