I'm writing a ReactJS app where I have a provider class (AuthProvider.js) handle Firebase authentication. Several of its children use the auth state. Everything worked fine for about a month, but last weekend we started having problems, probably because of some upgrade and I'm trying to troubleshoot. Basically, in the AuthProvider component, I have a currentUser state that's supposed to be null when no one is logged in or contain some data about the current user when there is one. Could be just the UID. Could be the full user object. Could be a boolean value. At this point we're not picky. Basically, when I try the textbook approach of
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged(user => {
setCurrentUser(user);
});
// Cleanup subscription on unmount
return () => unsubscribe();
}, []);
in the AuthProvider class (with or without useEffect), I get the "Rendered fewer hooks than expected." I heard some cliche about how using setState in callback functions is a bad idea, but I have no problems when setting errors (another state object that gets exported like currentUser).
Is there a safe and reliable way for me to observe the firebase state from AuthProvider's child components, with minimal code duplication? As is common, I have several cases where I display one component to the guests and another to the members, so the state is important to me.