0

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?

  • I don't see you updating `userStats` anywhere, so might that explain why it still has its default value? If not: did you already run the code in a debugger? I recommend setting a breakpoint on `setUserStats(userStatsDocs);` and seeing if the debugger reaches that, and whether `userStatsDocs` is what you'd expect. – Frank van Puffelen Feb 20 '22 at 18:25
  • @FrankvanPuffelen I'm using `setUserStats` to update `userStats`, By default value I meant the initial state I set `userStats` at, which was `[]`. I'm using Expo and running my app on the cli and seeing the logs there. It's strange because initially the userStats are set as an empty array, but when I change any code in my app and the app refreshes they suddenly appear – Nima Pourjafar Feb 21 '22 at 04:41
  • Setting state is an asynchronous operation, so it isn't immediately completed once the call to `setUserStats` returns. See https://stackoverflow.com/search?q=%5Breactjs%5D+set+state+asynchronous – Frank van Puffelen Feb 21 '22 at 04:50
  • @FrankvanPuffelen so if I set the state asynchronously it should solve the issue? – Nima Pourjafar Feb 22 '22 at 21:22

0 Answers0