Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

347
Vistas
Trouble fetching token from localstorage - React

I'm new with react and i'm trying to create a basic login function using local storage and tokens.

I can see in my devtools that a token is actually stored but when i refresh the page, my application seems to have some trouble fetching it.

These are the two js-files in which i think the problem is located:


function Mypage () {
   
    const { token, setToken } = useToken();

     if(!token) {
        return <Login setToken={setToken} />
    }
 
  return (
      <>
    <h1>My page</h1>
    </>
  )
}

export default Mypage

export default function useToken() {
  
     const getToken = () => {
    const tokenString = localStorage.getItem('token');
    const userToken = JSON.parse(tokenString);
    return userToken?.token
  };    

   /*    const getToken = () => {
        const token = localStorage.getItem("token");
        return token !== null;
      };   */

  const [token, setToken] = useState();

  const saveToken = userToken => {
    localStorage.setItem('token', JSON.stringify(userToken));
    setToken(userToken.token);
  };

  return {
    setToken: saveToken,
    token
  }
}

I tried to mess around with two different const in which the commented out did work in "Mypage", but i would like it to be gathered in the same function "useToken".

Can anyone please give some input in where i might be messing up?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

What I can see from your code is that there is a function to getToken which returns the token but you are not getting the token. In return, call the getToken function like you set saveToken.

return { 
   setToken: saveToken, 
   token: getToken 
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda