in the following code snippet, I'm trying to set to use the data from the snapshot listener outside of its scope, so I decided to use a useState
hook for it, but my data isn't being properly set.
useEffect(() => {
const unsubscribeAuth = onAuthStateChanged(auth, (authUser) => {
if (authUser) {
const userStatsQuery = query(
collection(db, "Users", authUser.uid, "UserStats")
);
const unsubscribeUserStats = onSnapshot(
userStatsQuery,
(userStatsSnapshot) => {
const userStatsDocs = [];
userStatsSnapshot.forEach((doc) => {
userStatsDocs.push(doc.data() as UserStats);
});
setUserStats(userStatsDocs);
console.log(userStatsDocs);
console.log(userStats);
}
);
setIsLoading(false);
} else {
setUser(null);
setIsLoading(false);
}
});
return () => {
unsubscribeAuth();
};
}, []);
Here I also have an auth state handler to check if the user is logged in to query for the stats.
console.log(userStatsDocs)
returns the data properly in a typed format, but console.log(userStats)
returns an empty array (the states initial value)
Any help?