How to use Firebase Firestore's `docChanges` method?

3.8k views Asked by At

in an action in a react native app using react-native-firebase, I create a Firestore snapshot listener:

listener:

export const onAgendaChange = (uid, role, dispatch) => {
    // query based off role
    let query;
    if (role == 'Receiver') {
        query = 'receiver.uid';
    } else {
        query = 'sender.uid';
    }

    console.log('(actions/agenda) Firestore Read: getAgenda()');

    return firebase
        .firestore()
        .collection('events')
        .where(query, '==', uid)
        .orderBy('date')
        .onSnapshot((querySnapshot) => {
            const agenda = []

            querySnapshot.forEach((doc) => {
                let event = doc.data();
                event.id = doc.id;
                agenda.push(event);

                dispatch({ type: types.LOAD_AGENDA_SUCCESS, payload: agenda });
            });

            querySnapshot.docChanges().forEach(function (change) {
                if (change.type === "added") {
                    console.log("Add heard: ", change.doc.data());
                }
                if (change.type === "modified") {
                    console.log("Modified heard: ", change.doc.data());
                }
                if (change.type === "removed") {
                    console.log("Removed heard: ", change.doc.data());
                }
            });
        });
};

one problem im observing is on initial app load, when this listener executes, it returns an error:

TypeError: querySnapshot.docChanges is not a function. (In 'querySnapshot.docChanges()', 'querySnapshot.docChanges' is an instance of Array)

the next issue im observing is that, if the app is reloaded, the error above is not generated, so if a document in the collection referenced is changed, the docChanges() still does not log anything. this is taken directly from firebase docs. And when using onSnapshot() on 'where' or 'orderBy', the callback receives a querySnapshot object, which does indeed have docChanges() as a method. So any thoughts?

1

There are 1 answers

1
Jim On

This issue is a result of following firebase docs too closely, while using react-native-firebase.

While the library does mirror 95% of firebase docs, in this case, it doesn't.

with react-native-firebase, docChanges is a property, not a function, so you want to use:

querySnapshot.docChanges.forEach(function (change) {
  if (change.type === "added") {
    console.log("Add heard: ", change.doc.data());
  }
  if (change.type === "modified") {
    console.log("Modified heard: ", change.doc.data());
  }
  if (change.type === "removed") {
    console.log("Removed heard: ", change.doc.data());
  }
});