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