At the moment, I’m fetching documents from my firestore collection but if I set an ID generally it won’t return anything, until I hardcode the ID in the Doc, here’s my code…
useEffect(() =>{
// LISTEN (REALTIME)
const fetchData = async (id) =>{
const docRef = doc(db, "users" , "DRrJ5zVL1YdP4wVs32aC");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
const theData = docSnap.data();
console.log('getUserDoc() setting userInfo:', theData);
setUserInfo(theData);
console.log("Document data:", docSnap.data());
} else {
// docSnap.data() will be undefined in this case
console.log("No such document!");
}
}
fetchData();
}, [id]);
I have a lot of documents in my collection and I want to only retrieve the required ID when I’m to update a doc..
2
Answers
If I’m not mistaken what you want to do is fetch the documents without referencing an id.
For that you will need to use, getDocs() rather than getDoc.
This will allow you to query a collection of items rather than a single item.
Here is a snippet from the firebase docs:
That typically happens if
id
is undefined. Please debug locally, as the best way to find this out is in the local debugger, by inspecting the variables.Set a breakpoint on each line of the code you shared, run the code in a debugger, and then check the value of each variable on each line to determine the first line that doesn’t do what you expect it to do.
You’ll see that
id
is empty when you pass it to Firestore.