Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 989
Tristan Trainer Avatar asked Mar 26 '19 21:03

Tristan Trainer


People also ask

How do I use Firebase authentication in Reactjs?

In the Firebase console, go to Authentication, then Sign in Method, and enable the Email/Password method. Now, we need to destructure the getAuth that we imported. So, in the handleAction function, let's do it. Now, let's create a user by using the createUserWithEmailAndPassword function.

Can we connect Firebase with React?

To integrate Firebase into our React app, we need to first get the web configuration object and then use it to initialize Firebase in our react app. Copy the config to the clipboard; we'll need it later on to initialize Firebase. Then, click Continue to console to complete the process.

What are React Firebase hooks?

A set of reusable React Hooks for Firebase. This documentation is for v5 of React Firebase Hooks which requires Firebase v9 or higher.

What is onAuthStateChanged?

onAuthStateChanged(FirebaseAuth auth) This method gets invoked in the UI thread on changes in the authentication state: Right after the listener has been registered. When a user is signed in. When the current user is signed out.


1 Answers

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>  );  
like image 83
Shubham Khatri Avatar answered Oct 22 '22 17:10

Shubham Khatri