user1149620
user1149620

Reputation: 873

Firebase and ReactJS - Authentication Using Local Storage

I would like to use localstorage to persist the auth state to avoid slow page content on refreshes. I've read about this elsewhere but unsure how to implement in my case. Could anyone help me work out how to edit the below to make it work please?

This example is similar but I'm not sure how to apply it to my case.

import React from 'react';
import { firebase } from '../firebase';
import PropTypes from 'prop-types';

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

      this.state = {
        authUser: null,
      };


    }

    getChildContext() {
      return {
        authUser: this.state.authUser,
      };
    }

    componentDidMount() {
      firebase.auth.onAuthStateChanged(authUser => {
        authUser
          ? this.setState(() => ({ authUser }))
          : this.setState(() => ({ authUser: null }));
      });
    }
    render() {
      return (
        <Component />
      );
    }
  }


  WithAuthentication.childContextTypes = {
    authUser: PropTypes.object,
  };

  return WithAuthentication;
}

export default withAuthentication;

Upvotes: 1

Views: 2419

Answers (1)

Arber Sylejmani
Arber Sylejmani

Reputation: 2108

Easy, just replace:

this.setState(() => ({ authUser }))

with

localStorage.setItem('authUser', JSON.stringify(authUser))

or

localStorage.removeItem('authUser')

to remove it

then you can read it:

JSON.parse(localStorage.getItem('authUser'))

instead of this.state.authUser

and in componentDidMount check if localStorage.getItem('authUser') exists before making the call again.

Upvotes: 5

Related Questions