Last Updated on June 17, 2024
AuthContext
import React, {useState} from "react"; export interface AuthContextType { isLoggedIn: boolean, logIn: () => void, logOut: () => void, } const AuthContextDefault: AuthContextType = { isLoggedIn: false, logIn(): void { }, logOut(): void { } }; const AuthContext = React.createContext(AuthContextDefault); export const AuthContextProvider = (props: any) => { // we need to initialize state from local storage because we should keep users logged in on page refresh const [isLoggedIn, setIsLoggedIn] = useState(() => { if (localStorage.getItem("isLoggedIn") === "1") { return true; } return false; }); const logInHandler = () => { setIsLoggedIn(true); // save in local storage localStorage.setItem("isLoggedIn", "1"); }; const logOutHandler = () => { setIsLoggedIn(false); // remove from local storage localStorage.removeItem("isLoggedIn"); } return <AuthContext.Provider value={{isLoggedIn: isLoggedIn, logIn: logInHandler, logOut: logOutHandler}}> {props.children} </AuthContext.Provider> ; }; export default AuthContext;
index
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import {BrowserRouter} from "react-router-dom"; import {AuthContextProvider} from "./context/AuthContext"; ReactDOM.render( <BrowserRouter> <React.StrictMode> <AuthContextProvider> <App/> </AuthContextProvider> </React.StrictMode> </BrowserRouter> , document.getElementById('root') ); reportWebVitals();
Login
import AuthContext from "../context/AuthContext"; import {useContext} from "react"; function Login() { const authCtx = useContext(AuthContext); return ( <div className="m-2"> <div> <span>Username : </span> <input type="text" className="input input-bordered w-full max-w-xs ml-2" placeholder="Enter Username"/> </div> <div> <span>Password : </span> <input type="password" className="input input-bordered w-full max-w-xs ml-2" placeholder="Enter Password"/> </div> <div className="mt-4"> <button type="button" className="btn" onClick={authCtx.logIn}>Login</button> <button type="button" className="btn ml-2" onClick={authCtx.logOut}>Logout</button> </div> </div> ); } export default Login;
User
import AuthContext from "../context/AuthContext"; import {useContext} from "react"; function User() { const authCtx = useContext(AuthContext); return ( <div> {authCtx.isLoggedIn && "Logged in"} {!authCtx.isLoggedIn && "Logged out"} </div> ) } export default User;
References
https://reactjs.org/docs/context.html