react-firebase-hooks icon indicating copy to clipboard operation
react-firebase-hooks copied to clipboard

useAuthState being called multiple times on render

Open armynante opened this issue 3 years ago • 0 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 avatar Jun 15 '22 16:06 armynante