Search code examples
javascriptfirebasereact-nativegoogle-cloud-firestore

Getting {"_h": 0, "_i": 0, "_j": null, "_k": null} when trying to get data from firebase firestore


I am creating an app in react native and trying to get some data from my firestore collection. I created the collection like this:

db.collection("admin-users").add({email: "adminuseremail"})

Here the db is a firebase.firestore() object. I am trying to get the data like this:

const snapshot = db.collection("admin-users").get();
snapshot.docs.map((doc) => doc.data());

But I am geting an error TypeError: Cannot read property 'map' of undefined. When I try to log snapshot I get {"_h": 0, "_i": 0, "_j": null, "_k": null} in my terminal.

This is how my firebase rules configuration looks like:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

This problem can occur for incorrect promise handling, like not using async/await. How would I use await in my react native app?


Solution

  • get() is an asynchronous operation that returns a Promise, so you're displaying the data of that promise rather than of the document in the database.

    If you're already in an async context, you can use await to wait for the promise to complete:

    const snapshot = await db.collection("admin-users").get();
    snapshot.docs.map((doc) => doc.data());
    

    If you can't use await, you can always use then to accomplish the same:

    db.collection("admin-users").get().then((snapshot) => {
      snapshot.docs.map((doc) => doc.data());
    });
    

    Dealing with asynchronous operations like this is very common in modern web development, so I recommend reading up on it with: