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

323
Visualizações
How to set the State when using AppContext()?

when I tray to set the state userHasAuthenticated in login function with true , it return false in console.log(isAuthenticated) ( stay the same in App.js 'false' )?

and I want to use it in Home Component the same probleme 'false';

  //----------------------in App.js----------------------

var [isAuthenticated, userHasAuthenticated] = useState('false');

<AppContext.Provider value={{ isAuthenticated, userHasAuthenticated }}>
//...
</AppContext.Provider>


//-------------- in Login.js---------------------

const { isAuthenticated,userHasAuthenticated } = useAppContext();

const login = () => {

    userHasAuthenticated('true'); 
    console.log(isAuthenticated);  //  false ?
     window.location.assign("/Home");

} 


  //  ---------------------in Home.js------------------------

 const { isAuthenticated,userHasAuthenticated } = useAppContext();
        console.log(isAuthenticated);// --->false ?


 //-------------- in context.js---------------------
    
      export const AppContext = createContext(null);
    
        export function useAppContext() {
          return useContext(AppContext);
        }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

For the most part this code seems right, the only thing thats wrong here from what I can tell is that you're attempting to console.log the isAuthenticated state immediately after setting it. This won't work because state setting is asynchronous, meaning you can't expect it to be updated immediately.

You could try this to see if the state changes:

//-------------- in Login.js---------------------

const { isAuthenticated, userHasAuthenticated } = useAppContext();

useEffect(() => {
  console.log(isAuthenticated); // this should be "true" after `login` has run
}, [isAuthenticated]);

const login = () => {
  userHasAuthenticated('true'); 
  console.log(isAuthenticated); // this should be "false"
  window.location.assign("/Home");
}
about 4 years ago · Juan Pablo Isaza Relatório

0

remember that your data of your Context is in MEMORY, everytime that you refresh your Application, App.js it will be called and renderize again, so it will call your context and it's create once again as false. Thats why you're getting 'FALSE' when you call isAuthenticated except in Login page

You better save your data in localstorage and get it from there everytime you refresh or navigate through your app, and thats will keep all the information save in your useAppContext() hook.

App.js:

const [isAuthenticated, userHasAuthenticated] = useState(localStorage.getItem('user') || 'false');

Try this in your Login.js:

export const Login = (props) => {

const {isAuthenticated, userHasAuthenticated} = useAppContext();



useEffect(() => {
    userHasAuthenticated('true');
    localStorage.setItem('user', 'true'); // set user to authenticated
}, []);



return (
    <>
        <h1>isAuthenticated =  {isAuthenticated}</h1>
    </>
);

};

And then get the data from your useAppContext():

export const Home = (props) => {

const { isAuthenticated } = useAppContext();

return (
    <>
        <h1>isAuthenticated = {isAuthenticated}</h1>
    </>
);

};

Result:

enter image description here

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