CSFrequency / react-firebase-hooks

React Hooks for Firebase.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useAuthState being called multiple times on render

armynante opened this issue · comments

I'm using the useAuthState hook and I'm seeing there are multiple calls each time the page is loaded.

Is this expected behavior? I'm new to nextJS/React and not sure if the useEffect hook is being triggered due to a bug in my code or unexpected behavior from the authState hook.

I expected the useEffect hook to be only triggered when the authUser object changes. Is it just calling back to the firebase API on each page refresh? I thought it was only listening for auth state changes?

Thanks in advance, and please excuse my ignorance if this is expected behavior!

import { useState, useEffect } from 'react'
import { auth, googleAuthProvider, firestore } from './firebase';
import { useAuthState } from 'react-firebase-hooks/auth';

export function useUserData() {
  const [authUser] = useAuthState(auth);
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
 
  useEffect(() => {
    // turn off realtime subscription
    let unsubscribe;
    if (authUser) {
      const ref = firestore.collection('users').doc(authUser.uid);
      unsubscribe = ref.onSnapshot((doc) => {
        // adds the user's favorites and user name to the user object
        setUser(doc.data());
      });
    } else {
      setUser(null);
    }
    console.log('authUser', authUser);
    
    return unsubscribe;
  }, [authUser]);
 
 return {
    authUser,
    user,
    loading,
    signInWithGoogle,
    favoriteVenue,
    signOut,
  };
}

console trace

localhost:3000:venues 2022-06-15 11-54-29

network calls to google api

localhost:3000:venues 2022-06-15 12-10-33

@armynante I've just checked with v5.1.0 (which has just been released) and I can no longer reproduce this error. There were some changes included in this release that may have accounted for the additional renders.

I'm going to close, but please feel free to reopen if you are still seeing this problem.