By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – Problems with data persistence in the state and token loss
JavaScript

Javascript – Problems with data persistence in the state and token loss

Admin
Last updated: 2023/12/24 at 1:49 PM
Admin
Share
6 Min Read
Problems with data persistence in the state and token loss

Problem:

I am trying to privatize some routes with JWT, everything is fine when logging in the data is saved in the state of AuthProvider as it corresponds as well as the token but when I reload the page the data is saved in a “subfield” of the state and the user token is lost somehow. This causes me problems because when the page is reloaded it redirects to the login again (public path) which is correct as long as the user is not logged in.

Contents
Problem:Solution:

AuthProvider

import { useState, useEffect, createContext } from "react";
import clientAxios from "../config/ClientAxios";
import { useNavigate } from "react-router-dom";

const AuthContext = createContext();

const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState({});

  const navigate = useNavigate();
  
  useEffect(() => {
    const authUser = async () => {
      const token = localStorage.getItem("token");
      
      if (!token) {
    
        
        return;
      }
      const config = {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      };
      try {
        const data = await clientAxios("/usuarios/perfil", config);
        setAuth(data);
        navigate('/inicio')
        
      } catch (error) {
        
        setAuth({});
      }
    };

    authUser();
  }, []);

  return (
    <AuthContext.Provider
      value={{
        auth,
        setAuth,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
export { AuthProvider };

export default AuthContext;

ProtectedRoute

import React from "react";
import { Outlet, Navigate } from "react-router-dom";
import useAuth from "../hooks/useAuth";
import Header from "../components/Header";

const ProtectedRoute = () => {

  const { auth } = useAuth();

  return(
    <div>
      
       {auth._id ? (
        <div className="bg-gray-100">
          <Header/>
          <div className="md:min-h-screen">
            <main>
             <Outlet/>
            </main>
            
          </div>
        </div>
       )
       :<Navigate to="/"/> }
      
    </div>
  ) 
};

export default ProtectedRoute;

useAuth

import { useContext } from "react";
import AuthContext from "../context/AuthProvider";

const useAuth = () => {
  return useContext(AuthContext);
};

export default useAuth;

Login

    import { Link, useNavigate } from "react-router-dom";
import { useState } from "react";
import Alert from "../components/Alert";
import clientAxios from "../config/ClientAxios";
import useAuth from "../hooks/useAuth";
import { AuthProvider } from "../context/AuthProvider";

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [alert, setAlert] = useState({});

  const {setAuth}=useAuth()


  const navigate=useNavigate()

  const handleSubmit = async (e) => {
    e.preventDefault();
    if ([email, password].includes("")) {
      setAlert({
        msg: "Hay uno o mas campos vacios",
        error: true,
      });
      return;
    
    }
    try {
      const {data}=await clientAxios.post('/usuarios/',{email,password})
      setAlert({})
      localStorage.setItem('token',data.token)
      setAuth(data)
      navigate('/inicio')
    } catch (error) {
      setAlert({
        msg:error.response.data.msg,
        error:true
      })
    }
  };

  const { msg } = alert;
  return (
    <div>
      <h1 className="text-sky-600 font-black text-4xl capitalize mt-3">
        Bienvenido de vuelta !
      </h1>
      <h3 className="text-gray-400 text-xl font-black">
        {" "}
        Inicia sesion y mejora tu
        <span className="text-sky-500"> ambiente laboral</span>
      </h3>

      {msg && <Alert alert={alert} />}
      <form onSubmit={handleSubmit} className="my-5">
        <label
          htmlFor="email"
          className=" font-bold uppercase block text-xl text-gray-600"
        >
          Email
        </label>
        <input
          id="email"
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Email Laboral"
          className="w-full mt-3 p-3 border rounded-xl bg-gray-200 cursor-pointer"
        />
        <label
          htmlFor="password"
          className=" font-bold uppercase block text-xl text-gray-600 mt-3"
        >
          Contraseña
        </label>
        <input
          id="password"
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Contraseña"
          className="w-full mt-3 p-3 border rounded-xl bg-gray-200 cursor-pointer"
        />

        <input
          type="submit"
          value="Iniciar Sesion"
          className="bg-sky-700 text-white w-full py-3 mt-5 font-bold rounded-md uppercase hover:cursor-pointer hover:bg-sky-900 transition-colors"
        />
      </form>
      <nav>
        <Link
          className="hover:underline block text-center my-5 text-slate-500 font-semibold uppercase text-sm"
          to="forget-password"
        >
          Cambia tu Contraseña
        </Link>
      </nav>
    </div>
  );
};

export default Login;

This is what should persist even when you reload the page. This happens every time you login.

This happens when I reload the page and it returns me to my Login. It does not help me to save the data in the State’s data hood because I can not access and verify from ProtectedRoute that there is an id because it verifies directly from the State.

The normal flow should be that when the page is reloaded the user’s data is not lost, nor the token, since this is necessary to perform other actions within the other private routes.

Solution:

Your protected routes need to know if you are still loading your auth, you can try something like

const AuthProvider = ({ children }) => {
  const [auth, setAuth] = useState({});
  const [isLoading, setIsLoading] = useState(true); // start of with loading as true
  const navigate = useNavigate();
  
  useEffect(() => {
    const authUser = async () => {
      const token = localStorage.getItem("token");
      
      if (!token) {
        setIsLoading(false); // set to false on early exit

        return;
      }

      const config = {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      };

      try {
        const { data } = await clientAxios("/usuarios/perfil", config); // destructure data from response
        setAuth(data);
        navigate('/inicio')
        
      } catch (error) {
        
        setAuth({});
      } finally {
        setIsLoading(false); // set isLoading to false after your async logic is done
      }
    };

    authUser();
  }, []);

  return (
    <AuthContext.Provider
      value={{
        auth,
        setAuth,
        isLoading,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
const ProtectedRoute = () => {

  const { auth, isLoading } = useAuth();
  
  if (isLoading) { // don't do any redirects while loading, just wait
    return <div>authenticating...</div>;
  }

  return(
    <div>
      
       {auth._id ? (
        <div className="bg-gray-100">
          <Header/>
          <div className="md:min-h-screen">
            <main>
             <Outlet/>
            </main>
            
          </div>
        </div>
       )
       :<Navigate to="/"/> }
      
    </div>
  ) 
};

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article How to find a property of one object by matching a different property to another object Javascript – How to find a property of one object by matching a different property to another object
Next Article how to only submit data change in react hook form Javascript – how to only submit data change in react hook form
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?