'Firebase and React Native subcribe to changes (onSnapshot) not working properly
I am having trouble subscribing to changes in Firebase's Firestore. I am developing my first React Native project with Firebase, therefore i am not really familiar with Firebase.
The Firebase connection is working: I can add and read data from the Firstore.
So far I have tried to replicate this issue: React useState and Firebase onSnapshot which did not work for me.
useEffect(() => {
const q = query(collection(db, "rooms"), where("active", "==", "true"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
setUser(querySnapshot);
});
console.log("User: " + user);
return () => {
unsubscribe();
};
}, []);
When I run it I get the following output User: undefined
I have also tried this approach:
const q = query(collection(db, "rooms"), where("active", "==", "true"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc);
});
});
unsubscribe();
That's not working either.
Here you can see my Firestore: Firestore
Is there anything I am missing? Your help is really appreciated!
Solution 1:[1]
onSnapshot , setUser and other calls that manipulate state, are asynchronous, so you have to make sure you log them after the asynchronous operation has completed.
That's why your call to setUser(querySnapshot); is inside the callback, as that ensures it happens after the querySnapshot is available from the database.
If you want to see the value that you get from the database, log it inside the callback like this:
const unsubscribe = onSnapshot(q, (querySnapshot) => {
console.log("Snapshot: " + querySnapshot.size);
setUser(querySnapshot);
});
Similarly, if you want to show the updated state, you can pass a callback to setUser, which then is called once the state is updated:
const unsubscribe = onSnapshot(q, (querySnapshot) => {
console.log("Snapshot: " + querySnapshot.size);
setUser(querySnapshot, () => {
console.log("User: " + user.size);
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Frank van Puffelen |
