Reputation: 589
Just a FYI; I have checked all the previously asked questions and none of them relate directly to my problem. I have documents in a collection and i’m trying to listen to changes to the documents. I am first using get()
to retrieve all the documents in the collection and then looping through all of them to listen to changes. This might be the wrong way to do this but i couldn't find anything else in the docs or online.
My problem is that because i’m using get()
first, the onSnapshot listener isn't getting invoked unless i manually refresh. I’m trying to get it to show changes automatically as they happen. For example, if i add a document to the collection i expect it to run.
Here's my code:
const db = firestore().collection('Networks');
const NetworksListScreen = ({ navigation }) => {
const [state, setState] = useState({ networks: [] });
const { networks } = state;
const getNetworks = async () => {
try {
await db.get().then((querySnapshot) => {
let networks = [];
querySnapshot.forEach(doc => {
db.doc(doc.id).onSnapshot(newDoc => {
console.log(newDoc.id, '=====>', newDoc.data());
networks.push(doc.data());
});
});
setState({
networks: networks
});
});
} catch (err) {
console.log(err)
}
};
useEffect(() => {
getNetworks();
}, []);
}
Any help is really appreciated.
Upvotes: 0
Views: 1982
Reputation: 317372
It's going to be far easier for you to instead use onSnapshot on the entire collection (a CollectionReference is a Query that finds all documents). The snapshot you receive will contain information about each document that changed (added, changed, or removed) since the last time your listener was called.
firestore().collection('Networks').onSnapshot(querySnapshot => {
// handle changes to documents in the collection here
})
Upvotes: 3