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
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
get()
is an asynchronous operation that returns aPromise
, 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 useawait
to wait for the promise to complete:If you can’t use
await
, you can always usethen
to accomplish the same:Dealing with asynchronous operations like this is very common in modern web development, so I recommend reading up on it with: