Search code examples
reactjsfirebasereact-nativefirebase-realtime-databaseevent-listener

how to set up firebase realtime database eventListener in react native


I am trying to add an event listener to my react native app that triggers on changed however it does not trigger until I refresh the application. I think I am setting up the event listener incorrectly but I do not know how else to do it.

Here is my code:

render(){

    Firebase.database()
    .ref('/UserToQuestion/' + Firebase.auth().currentUser.uid)
    .orderByChild("Question")
    .on('value', snapshot => {

         console.log('-----------');



        var i = 0
        snapshot.forEach(function(childSnapshot) {



            var childData = childSnapshot.val();



            titlesArray.push(childData.Title)
            contentArray.push(childData.Question)
            dataArray.push({title:titlesArray[i],content:contentArray[i]})
            i++
            console.log( titlesArray);



   });

 })

Putting it outside the render method gives an error of the currentUser.uid being undefined, but I think that the listener only being triggered on render is the problem so how would I have it always being triggered?

Thank you


Solution

  • You need to set it up so you create the firebase reference when the component is being constructed. I think something like this should work. I've added comments to explain what I've done:

    class MySuperAwesomeClass extends React.Component {
      // this will be a fixed reference you can use to attach/detach the listener
      firebaseRef;
    
      constructor(props) {
        super(props);
    
        // assign a reference to this component's firebaseRef member
        this.firebaseRef = Firebase.database().ref(
          `/UserToQuestion/${Firebase.auth().currentUser.uid}`
        );
    
        // grab the data from the server and call this.onFirebaseValueChanged every time it changes
        this.firebaseRef.orderByChild("Question").on("value", this.onFirebaseValueChanged);
      }
    
      componentWillUnmount() {
        // detach all listeners to this reference when component unmounts (very important!)
        this.firebaseRef.off();
      }
    
      onFirebaseValueChanged = snapshot => {
        console.log("-----------");
        // I created these arrays because they didn't seem to exist
        const titlesArray = [];
        const contentArray = [];
        const dataArray = [];
    
        // use let instead of var because it's changing
        let i = 0;
        snapshot.forEach(childSnapshot => {
          // use const instead of var
          const childData = childSnapshot.val();
    
          titlesArray.push(childData.Title);
          contentArray.push(childData.Question);
          dataArray.push({title: titlesArray[i], content: contentArray[i]});
          i++;
          console.log(titlesArray);
        });
      };
    
      render() {
        return <Text>Render method shouldn't be talking to the server!</Text>;
      }
    }