Persisting 'isAuthenticated' state after refresh in React

Viewed 156

After I log in the state of isAuthenticated is true but when I refresh the state change to false ! so what is the best solution to keep isAuthenticated to true after I log in ? in AuthService the code is :

const Axios = require('axios');

export default {
  isAuthenticated: () => {
    return Axios({
      url: 'http://localhost:4000/user/authenticated',
      method: 'GET',
    })
      .then((res) => {
        if (res.status !== 401) return res.json().then((data) => data);
        else
          return {
            isAuthenticated: false,
            user: {
              firstName: ' ',
              lastName: ' ',
              email: ' ',
            },
          };
      })
      .catch((err) => {
        console.log('isAuthenticated err :' + err);
        return {
          isAuthenticated: false,
          user: {
            firstName: ' ',
            lastName: ' ',
            email: ' ',
          },
        };
      });
  },
};

and in AuthContext:

import React, { createContext, useState, useEffect } from 'react';
import AuthService from '../Services/AuthService';

export const AuthContext = createContext();

export default ({ children }) => {
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    AuthService.isAuthenticated().then((data) => {
      console.log('is authenticated  :' + data.isAuthenticated);
      setUser(data.user);
      setIsAuthenticated(data.isAuthenticated);
      setIsLoaded(true);
    });
  }, []);

  return (
    <div>
      {!isLoaded ? (
        <h1>Loading</h1>
      ) : (
        <AuthContext.Provider value={{ user, setUser, isAuthenticated, setIsAuthenticated }}>
          {children}
        </AuthContext.Provider>
      )}
    </div>
  );
};

and in index.js I wrapped the app between Auth provider

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.css';
import AuthProvider from './context/AuthContext';

ReactDOM.render(
  <AuthProvider>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </AuthProvider>,
  document.getElementById('root'),
);

and here is the app.js:

import React, { useContext } from 'react';
import Navigation from './components/Navigation';
import Home from './components/Home';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Dashboard from './components/user/Dashboard';

function App() {
  const { isAuthenticated } = useContext(AuthContext);

  return (
    <Router>
      {isAuthenticated ? (
        <Switch>
          <Route path="/dashboard" component={Dashboard} />
        </Switch>
      ) : (
        <div className="App">
          <Navigation />
          <Switch>
            <Route path="/" exact component={Home} />
            <Route path="/produit" component={Produit} />
          </Switch>
        </div>
      )}
    </Router>
  );
}

export default App;
2 Answers
localStorage.setItem("user", "Hamza");

// refresh page...

localStorage.getItem("user"); // should return Hamza

You can use jwt-token to keep the data of the current user in local storage or session storage. I used RxJs in here.

From getCurrentUser function you can get the details of the current user.

You have to generate the jwt-token from the backend and receive it from the frontend and save it in the localStorage.Read more about using jwt-tokens https://jwt.io/introduction/

You can give it a try as below example:

AuthContext.js

import jwt_decode from "jwt-decode";

const [user, setUser] = useState({
isAuthenticated: false,
currentUser: "",
 });

useEffect(() => {
AuthService.getAuthStatus().subscribe((res) => {
    console.log(res);
      setUser({
        isAuthenticated: true,
        currentUser: jwt_decode(localStorage.jwtToken),
      });
   });
  console.log(state.currentUser);
 },[]);

AuthService.js

import { Subject } from "rxjs";

const isAuthenticated = new Subject(false);
const currentUser = new Subject();
const user = new Subject();

export const AuthService = {

isAuthenticated : ()=>{
return  Axios({
    url: "http://localhost:4000/user/authenticated",
    method: "GET",
    
}).then(res=>{
    if(res.status !== 401)
        .then(res =>{
    const { token } = res.data;
    localStorage.setItem("jwtToken", token);
    isAuthenticated.next(true);
 });
    else
    return {
        isAuthenticated : false, 
        user:{
            firstName:" ",
            lastName:" ",
            email:" "}};
})

setCurrentUser: (decoded) => {
setAuthToken(localStorage.getItem);
currentUser.next(decoded);
isAuthenticated.next(true);
},

getAuthStatus: () => isAuthenticated.asObservable(),
getCurrentUser: () => currentUser.asObservable(),
};
Related