It seems like onSnapshot is triggered again whenever I print something related to the data that I retrieved, without changing the data. Here is an example of code that works correctly for me, it prints the length of the collection once:
const [games, setGames] = useState([]);
useEffect(() => {
onSnapshot(collection(db, "games"), { includeMetadataChanges: false }, (snapshot) => {
setGames(
snapshot.docs.map((doc) => ({
id: doc.id,
item: doc.data(),
}))
);
console.log(games.length);
});
});
However, if I want to print the data I retrieved with
<div>
{games.map((game) => {
console.log(game.item);
return <>{game.id}</>;
})}
</div>
for example, it will infinitely repeatedly print the length of the collection then the data in the collection. Another example that breaks it is adding another print statement in the beginning of the onSnapshot handler:
snapshot.docChanges().forEach((change) => {
console.log(change.type);
});
this will repeatedly print "added" and then the length of the collection, even though nothing is being added to the collection. Does anyone know why this occurs?