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

后端 未结 2 691
旧巷少年郎
旧巷少年郎 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 15:13

    Hi the information from Shubham Khatri was very helpful and helped me to build my own component but he used Context to manage the state. If you just start learning react and firebase I found it easyer (even if not right) to have the state in my component.

    So the simple solution for me without using Context was to build it with react hooks only like this:

    const useAuth = () => {
      const fireUser = firebase.auth().currentUser;
      const [user, setUser] = useState(fireUser);
    
      useEffect(() => {
        const unsub = firebase.auth().onAuthStateChanged((user) => {
          user ? setUser(user) : setUser(null);
        });
        return () => {
          unsub();
        };
      });
      return user;
    };
    
    const HomeV2 = () => {
    
      const user = useAuth();
    
    
      return (
        
    React Hooks {user ?

    User is HERE

    :

    There's no user !

    }
    ); }; export default HomeV2;

提交回复
热议问题