auth-context.js
import React, { useState,useEffect } from "react";
const AuthContext = React.createContext({
isLoggedIn: false,
onLogout: () => {}, //for better ide autocompletion test in navigation <button onclick=ctx.onlogout autoretrived
onLogin:(email,password)=>{}
});
export const AuthContextProvider = (props) => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
useEffect(()=>{
const storedLocalStorage=localStorage.getItem('isLoggedIn');
if(storedLocalStorage==="1"){
setIsLoggedIn(true);
}
},[]);
const logoutHandler = () => {
localStorage.removeItem('isLoggedIn');
setIsLoggedIn(false);
};
const loginHandler = () => {
localStorage.setItem('isLoggedIn','1');
setIsLoggedIn(true);
};
return (
<AuthContext.Provider
value={{ isLoggedIn: isLoggedIn, onLogout: logoutHandler,onLogin:loginHandler }}
>
{props.children}
</AuthContext.Provider>
);
};
// exporting both files here AuthContextProvider and AUthcontext
export default AuthContext;
Navigation:
import React, {useContext} from 'react';
import AuthContext from '../../store/auth-context';
import classes from './Navigation.module.css';
const Navigation = () => {
const ctx= useContext(AuthContext); //changes: newly added this and imported useContext
return (
// <AuthContext.Consumer> //Removed these 3 lines
// {(ctx)=>{
// return (
<nav className={classes.nav}>
<ul>
{ctx.isLoggedIn && (
<li>
<a href="/">Users</a>
</li>
)}
{/* {props.isLoggedIn && ( */}
{ctx.isLoggedIn && (
<li>
<a href="/">Admin</a>
</li>
)}
{ctx.isLoggedIn && (
<li>
<button onClick={ctx.onLogout}>Logout</button>
</li>
)}
</ul>
</nav>
// )
// }}
// {/* will get data of auth context comp */}
// </AuthContext.Consumer>
);
};
export default Navigation;
APp.js
import React, { useContext } from 'react';
import Login from './components/Login/Login';
import Home from './components/Home/Home';
import MainHeader from './components/MainHeader/MainHeader';
import AuthContext from './store/auth-context';
function App() {
const ctx= useContext(AuthContext); // added new
//all moved to auth-context.js
// const [isLoggedIn, setIsLoggedIn] = useState(false);
// useEffect(()=>{
// const storedLocalStorage=localStorage.getItem('isLoggedIn');
// if(storedLocalStorage==="1"){
// setIsLoggedIn(true);
// }
// },[]);
// const loginHandler = (email, password) => {
// // We should of course check email and password
// // But it's just a dummy/ demo anyways
// localStorage.removeItem('isLoggedIn');
// localStorage.setItem('isLoggedIn','1');
// setIsLoggedIn(true);
// };
// const logoutHandler = () => {
// localStorage.setItem('isLoggedIn','0');
// setIsLoggedIn(false);
// };
return (
<React.Fragment>
{/* // <AuthContext.Provider value={{isLoggedIn:isLoggedIn,onLogout:logoutHandler}}> */}
<MainHeader/>
<main>
{!ctx.isLoggedIn && <Login/>}
{ctx.isLoggedIn && <Home/>}
</main>
{/* // </AuthContext.Provider> */}
</React.Fragment>
);
}
export default App;
index.js
root.render(<AuthContextProvider><App /></AuthContextProvider>);
No comments:
Post a Comment