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

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

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 Denunciar

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