skip to Main Content

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?

2

Answers


  1. Use Async/Await or any other JS operations to handle asynchronous operations

    In general, {"_h": 0, "_i": 0, "_j": null, "_k": null} error is due to incorrect Promise handling. For eg, not using async/await.

    For your case refer to https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document

    Login or Signup to reply.
  2. 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:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search