Home > Enterprise >  How to set the State when using AppContext()?
How to set the State when using AppContext()?

Time:05-04

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);
        }

CodePudding user response:

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");
}

CodePudding user response:

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

  • Related