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

253
Visualizações
reactjs: a context component function not updating its variable; usestate not working immediately?

I'm working on auth in my app, so I created a context to manage it:

import React, { useState } from "react";

const AuthContext = React.createContext({
    token: "",
    isLoggedIn: false,
    login: (token) => { },
    logout: () => { },
});

export const AuthContextProvider = (props) => {
    const [token, setToken] = useState(null);
    const [userIsLoggedIn, setUserLoggedIn] = useState(false)

    const loginHandler = async (token) => {
        setToken(token);
        setUserLoggedIn(true)
        console.log(userIsLoggedIn)   //prints false
    };

    const logoutHandler = () => {
        setToken(null);
        setUserLoggedIn(false)
    };

    const contextValue = {
        token: token,
        isLoggedIn: userIsLoggedIn,
        login: loginHandler,
        logout: logoutHandler,
    };


    return (
        <AuthContext.Provider value={contextValue}>
            {props.children}
        </AuthContext.Provider>
    );
};

export default AuthContext;

The problem is that when I call context.login('some token') from an outside component and then console.log(context.isLoggedIn) I get false the first time, but if I call context.login('some token') once again I get true. Every succesive time after that I get true now. It might have to do with the fact the "console.log(userIsLoggedIn)" inside the loginHandler says "false" (the first time the context.login is called) even though the setUserLoggedIn is right above it. I think the userIsLoggedIn variable is changed after the context is updated in the component it's used in, but I don't know how to fix that. I will appreciate any help on this

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You cannot rely on the value of userIsLoggedIn to have the value you passed to setUserLoggedIn immediately.

If you want to keep track of the userIsLoggedIn variable, you might consider something like this:

React.useEffect(() => {
  console.log(userIsLoggedIn)
}, [userIsLoggedIn])
about 4 years ago · Santiago Trujillo 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