React native firebase database on value change not triggered

Viewed 1479

I have a react native app and using firebase database.

I try to use the on or once functions to get items from database but I don't know what I am doing wrong because I don't get any data.

This is my code to get data from firebase database:

firebase.database().ref("messages/").once('value', snapshot => {console.log("snapshot value", snapshot)});

I try the command from above also with on instead of once and same result. The console.log is never called.

When I am adding messages everything it's ok and the messages appear in the firebase console. For adding messages I am doing like this:

firebase.database().ref("messages/").push(message);

For firebase I am using this library: rnfirebase.io

This are the versions used: React: 16.6.0-alpha.8af6728 React native: 0.57.4 React native firebase: 5.0.0

1 Answers

The Firebase once returns a promise so you have to use then after using value. The code should be like

 firebase.database().ref('tableNameHere').once('value').then(snapshot => {
      if(snapshot.exists()){
         console.log(snapshot.val());
      }
}).catch(err => console.log(err));

when using on value the function will invoke on change in value like on CRUD operation

 firebase.database().ref('tableNameHere').on('value', snapshot => {
              if(snapshot.exists()){
                 console.log(snapshot.val());
              }
        },(err) => console.log(err))
Related