Eduardo
Eduardo

Reputation: 1831

React-Native + Firebase : How to handle realtime updates

I am using react native + firebase. I need to update my list of docs everytime there is a new doc. so I found information about "real time updates" and using "onSnapshot":

let items = [];

firebase.firestore().collection("docs").onSnapshot(function(results) {

            results.forEach((doc) => {
                const item = doc.data()
                if (item) {
                    items.push(item);
                }
              });


    }, function(error) {
       console.log(error)
    })

If I return a value onSnapshot will run only once the idea is to keep it listening to changes, how should I implement that?

Upvotes: 1

Views: 2714

Answers (2)

Raja Ali
Raja Ali

Reputation: 1

import firestore from '@react-native-firebase/firestore';

export const fetchUserData = () => { return new Promise((resolve, reject) => {

const unsubscribe = firestore()
  .collection('Users')
  .onSnapshot(snapshot => {
    let changes= snapshot.docChanges();
    changes.forEach(change=>{
    console.log("change Happen",change.doc.data());
  });

  })

  .catch((error) => {
    console.log('Error fetching data:', error);
    reject([]);
  });




// Return the unsubscribe function to clean up the subscription if needed
return unsubscribe;

}); };

// This file only contains the fetchUserData function

Upvotes: 0

MIPB
MIPB

Reputation: 2471

I understand that you are using the React Native Firebase package (https://rnfirebase.io/)

You are correct, there is a function that listens to changes on the database in real time (for example, the number of likes on a post).

Check the docs here: Firestore Real Time Changes

This is the proposed code on the docs for listening to this type of changes:

function User({ userId }) {
  useEffect(() => {
    const subscriber = firestore()
      .collection('Users')
      .doc(userId)
      .onSnapshot(documentSnapshot => {
        console.log('User data: ', documentSnapshot.data());
      });

    // Stop listening for updates when no longer required
    return () => subscriber();
  }, [userId]);
}

In my experience with React Native Firebase, the real time changes work pretty well. Make sure your code is as explained in the official docs and you will be good to go.

Hope it helps.

Upvotes: 4

Related Questions