How do I use the Firebase onAuthStateChange with the new React Hooks?

后端 未结 2 690
旧巷少年郎
旧巷少年郎 2020-12-24 14:22

I am using Firebase to authenticate users for my application. I have created the SignIn and SignUp forms and can successfully create n

2条回答
  •  庸人自扰
    2020-12-24 14:57

    You can write a Custom Hook which registers an effect and returns the auth state

    const useFirebaseAuthentication = (firebase) => {
        const [authUser, setAuthUser] = useState(null);
    
        useEffect(() =>{
           const unlisten = firebase.auth.onAuthStateChanged(
              authUser => {
                authUser
                  ? setAuthUser(authUser)
                  : setAuthUser(null);
              },
           );
           return () => {
               unlisten();
           }
        });
    
        return authUser
    }
    
    export default useFirebaseAuthentication;
    

    and in any Component you can use it like

    const MyComponent = (props) => {
       const firebase = useContext(FirebaseContext);
       const authUser = useFirebaseAuthentication(firebase);
    
       return (...)
    }
    

    Index.jsx will have this code in it

    ReactDOM.render( 
        
           
       , 
       document.getElementById('root')); 
    

    This Firebase Provider is defined like this,

    import Firebase from './firebase';
    
    const FirebaseContext = createContext(); 
    export const FirebaseProvider = (props) => ( 
        
          {props.children} 
        
    ); 
    

提交回复
热议问题