Firestore make function trigger once opening the App, then after changes

Viewed 31

I want this function to trigger once I start the App, then every time there is a change in my firestore data.

export const getDuettsPlayer1 = (setDuetts) => {
  duettsRef.where("player1", "==", firebase.auth().currentUser.uid)
    .get()
    .then((querySnapshot) => {
      setDuetts(querySnapshot.docs.map(doc => doc.data()));
    })
    .catch((error) => {
      console.log("Error getting document:", error);
    });
}

I already tried it like this:

const getDuettsPlayer1 = (setDuetts) => {
  duettsRef.where("player1", "==", firebase.auth().currentUser.uid)
  .onSnapshot((querySnapshot) => {
      setDuetts(querySnapshot.docs.map(doc => doc.data()));
    })
    .catch((error) => {
      console.log("Error getting document:", error);
    });
}

, but then i got TypeError: undefined is not a function (near '...}).catch(function (error) {...') How do i do this correctly?

1 Answers

onSnapshot doesn't return a promise, so it doesn't have a catch method.

Instead you handle errors by passing in a second listener:

  duettsRef.where("player1", "==", firebase.auth().currentUser.uid)
  .onSnapshot((querySnapshot) => {
      setDuetts(querySnapshot.docs.map(doc => doc.data()));
    }, (error) => {
      console.log("Error getting document:", error);
    });

Also see the Firestore documentation on listening for errors

Related