Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

350
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda