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

140
Vistas
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 Respuestas
Responde la pregunta

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 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