1
votes

I started my Creating my react native android App using realtime database but later realised that i could'nt carry out some queries(like where) so i changed to cloud firestore but i have found trouble changing code meant for realtime database to cloud firestore. I have this for the real time database which works well

firebase.database().ref('/users').on('value', (snapshot) => {
      let data = snapshot.val();
      let items = Object.values(data);
      this.setState({items});
   }).catch(function(error) {
         var errorCode = error.code;
         var errorMessage = error.message;            
           this.setState({ errorMessage: errorMessage })            
       });

I have tried to yield the code above in cloud firestore as shown below but doesn't work(a typeerror pops up and states that snapshot.val is not a function).

firebase.firestore().collection('users').get().then((snapshot)=>{              
        let data = snapshot.val();
        let items = Object.values(data);
        this.setState({items});
     }).catch(function(error) {
         var errorCode = error.code;
         var errorMessage = error.message;            
           this.setState({ errorMessage: errorMessage })            
       });

This is in my database project cloud firestore instance How can i yield working corresponding cloud firestore code?

1
Your code isn't checking for errors, so something could be going wrong, and you wouldn't know. Also we can't see if you have any documents under "users", so your query could simply be returning nothing because there is no data. Please edit the question to explain in more detail what isn't working the way you expect. - Doug Stevenson

1 Answers

2
votes

Your code isn't working because it's not working with the Firestore API correctly. Your query:

firebase.firestore().collection('users').get()

Is going to fetch a QuerySnapshot with zero or more documents, depending on what you have in the collection. You will need to use the QuerySnapshot API to iterate the possible documents in the results. Right now, you are calling val() on the QuerySnapshot, which is not a valid method. The API is very different than Realtime Database.

Your code should instead iterate the documents in the results set to find out what the query returned, like this:

firebase.firestore().collection('users').get().then((querySnapshot) => {
    querySnapshot.forEach(snapshot => {
        let data = snapshot.data();
        console.log(data);
    }
})

I recommend reviewing the documentation for Firestore queries, and follow the patterns there. Again, it is very different than RealtimeDatabase, so you will not be able to reuse what you know about it for Firestore.