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

175
Visualizações
React : new tab or refresh doesn't read localStorage

I'm building a React app which requires authentification to use an API. So I keep the user token in my React context. Everything works fine as long as the user stay in the same session but, of course, whenever I open a new tab or refresh the current one, the context is lost. So I created a component that either stocks the token in localStorage (if there is a token) or retrieve said token from the localStorage.

I thought I had it figured out but... it doesn't work as expected. When I open a new tab, I am redirected to the login page (which is expected when there is no token).

I've checked what happens with some console logs and :

  • when I log in a first tab, the token is saved to the localStorage.
  • when I open a second tab, it looks like there is nothing stored in the localStorage.
  • but if I save my code again AFTER opening the second tag (to add anything useless), then the localStorage is not empty anymore and I'm logged in the second tab too.

Here is my token handler component (called directly in App.jsx) :

import { useContext, useEffect } from "react";

import { DisplayContext } from "../context/DisplayContext";

export default function TokenHandler() {
  const {
    setCurrentUser,
    userToken,
    setUserToken,
    setTokenLimit,
    setUserRole,
  } = useContext(DisplayContext);

  const retrievingToken = () => {
    let stockDate = new Date();
    if (localStorage.getItem("mddTheme") && !userToken) {
      const stockToken = localStorage.getItem("mddTheme");
      if (stockDate.getTime() < stockToken.exp) {
        setUserToken(localStorage.getItem("mddTheme"));
        setCurrentUser(stockToken.sub);
        setTokenLimit(stockToken.exp);
        setUserRole(stockToken.aud);
      } else {
        localStorage.removeItem("mddTheme");
      }
    }
    console.log(
      "retrieving token : ",
      userToken,
      localStorage.getItem("mddTheme")
    );
  };

  const stockingToken = () => {
    if (
      userToken &&
      (!localStorage.getItem("mddTheme") ||
        localStorage.getItem("mddTheme") !== userToken)
    ) {
      localStorage.setItem("mddTheme", userToken);
    }
    console.log(
      "stocking token : ",
      userToken,
      localStorage.getItem("mddTheme")
    );
  };

  useEffect(() => {
    console.log(
      "token handler : ",
      userToken,
      localStorage.getItem("mddTheme")
    );
    // if (userToken !== "") {
    stockingToken();
    // } else {
    retrievingToken();
    // }
  }, [userToken]);

  return <></>;
}

Any idea why a new tab can't read the storage on opening ?

about 4 years ago · Juan Pablo Isaza
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