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

134
Visualizações
LocalStorage does not persist

I have been trying to persist my token in the localStorage but everytime I referesh the page, the value turns to undefined.

Here is my code from App.tsx. I am using redux in my project but persisting using redux throws plenty of type errors. That is why I am going with local storage.

  const [isLoggedIn, setIsLoggedIn] = useState('');
  // @ts-ignore
  const user = useAppSelector(state=>state.user.currentUser.token);
  useEffect(()=>{
    const getToken = localStorage.getItem("token");
    if(getToken){
      setIsLoggedIn(getToken)
    }
  },[])

  useEffect(()=>{
    localStorage.setItem("token", user)
  },[user])

For extra reference, these are my routes

        <Route path="/userProfile" element={<UserProfile />} />
        <Route path="/login" element={user ? <Navigate to="/" /> : <Login />} />
        <Route path="/cart" element={<Cart />} />
        <Route path="/" element={<Home />} />
        <Route path="/product/:id" element={<SingleProduct />} />       

So far I have tried all that I know but I am still not able to figure out the root problem.

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

  useEffect(()=>{
    localStorage.setItem("token", user)
  },[user])

Your problem is from the above useEffect. Although it has dependency user (which is listening to user state changes), it's called when you render the component for the first time.

I'd propose you should add a condition to that useEffect like below

  useEffect(()=>{
    if(user) {
       localStorage.setItem("token", user)
    }
  },[user])

That would help you to prevent calling setItem with an undefined value of user.

about 4 years ago · Santiago Gelvez Relatório

0

Check user to undefined

user && localStorage.setItem("token", user)
about 4 years ago · Santiago Gelvez 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