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

若如初见. 提交于 2020-02-21 10:18:01

问题


I am using Firebase to authenticate users for my application. I have created the SignIn and SignUp forms and can successfully create new users and sign in with stored users. However the issue comes with maintaining the user logged in state after a Reload.

The way I have seen it done in tutorials is to use a HOC like the following to check if the current user is logged in.

const withAuthentication = Component => {
  class WithAuthentication extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        authUser: null,
      };
    }

    componentDidMount() {
      this.listener = this.props.firebase.auth.onAuthStateChanged(
        authUser => {
          authUser
            ? this.setState({ authUser })
            : this.setState({ authUser: null });
        },
      );
    }

    componentWillUnmount() {
      this.listener();
    }

    render() {
    return (
      <AuthUserContext.Provider value={this.state.authUser}>
        <Component {...this.props} />
      </AuthUserContext.Provider>
      );
    }
  }

  return withFirebase(WithAuthentication);
};

export default withAuthentication;

However I am looking to use the new React Hooks to remove the need for HOCs. I have already removed the withFirebase() HOC by using the React Context and useContext(FirebaseContext) to access a single instance of Firebase. Is there a way using the new hooks to mimic this withAuthentication HOC within components that I create?

I am using this tutorial

https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/

The section titled "Session Handling with Higher-Order Components" contains this part.

Thanks!


回答1:


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( 
   <FirebaseProvider> 
      <App /> 
   </FirebaseProvider>, 
   document.getElementById('root')); 

This Firebase Provider is defined like this,

import Firebase from './firebase';

const FirebaseContext = createContext(); 
export const FirebaseProvider = (props) => ( 
   <FirebaseContext.Provider value={new Firebase()}> 
      {props.children} 
   </FirebaseContext.Provider> 
); 


来源:https://stackoverflow.com/questions/55366320/how-do-i-use-the-firebase-onauthstatechange-with-the-new-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!