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

145
Visualizações
The state variable declared in context is not persisting its value

I am using a context state variable to store my token value when user signs in. And using that token through out my application. When I log in, the token is console logged on the login page. But it gives empty value on other pages even though I am using the context in all the files.

AuthContext.js

export const AuthContext = createContext();

export const AuthProvider = (props) => {
  const [authToken, setAuthToken] = useState("");
  const [authProtected, setAuthprotected] = useState(true);

  return (
    <AuthContext.Provider
      value={{
        token: [authToken, setAuthToken],
        authProtect: [authProtected, setAuthprotected],
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};

Login.js

const userAuth = (e) => {
    e.preventDefault();
    Axios.post(authApi, loginInfo).then((res) => {
      setJwtToken(res.data.idToken.jwtToken);
    });
  };
  console.log(jwtToken);

After log in, I use this in one of my pages and it logs an empty value

const { token } = useContext(AuthContext);
const [jwtToken, setJwtToken] = token;

console.log(jwtToken);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When the page reloads, the context is recreated. You need to use a useEffect within the context to refetch the information from the backend and save the token in case you are saving to some cookie or localstorange.

Put the token in the cookie and when it switches pages, retrieve the cookie by useEffect to save again in context

Note: when you switch pages, everything in the context is recreated, so when the page goes to get something from the context, it will be empty

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