Problem in implementing hardcoded Auth in Reactjs

Viewed 44

I want to implement a hardcoded auth in reactjs, i.e., if user enters a particular string then access is given otherwise not. My app.js code is as follows:

function App() {

    const[user, setUser]= useState(false);
    const[ID, setID]= useState('');
    const[IDError, setIDError]= useState('');

    const clearErrors = () =>{
        setIDError('');
    }


    const handleLogin=()=>{
        clearErrors();
        if(ID==="quantel123"){
            setUser(true);
        }else if(ID===""){
            setIDError("This field can't be empty. Access denied!");
        }else{
            setIDError("The ID entered is wrong");
        }
    };

    const handleLogout=()=>{
        if (window.confirm('Are you sure you want to Logout?')){
            setUser(false);
        }
    };

    useEffect(()=>{
        const authListener=()=>{
            if(user){
                setUser(user);
            }else{
                setUser(false);
            }
           
        };

        authListener();
    }, [user]);

  
  return (
    <Router>
    {user?(
        <Grid container direction="column">
            <Grid item>
                <Navbar />
            </Grid>
            <Grid item container>
                <Grid item xs={false} sm={2}>
                    <Sidebar handleLogout={handleLogout} />
                </Grid>
                <Grid item xs={12} sm={10}>
                    <Switch>
                        <Route exact path="/login"><Redirect to="/" /></Route>  
                        <Route exact path="/" component={Home}/>
                        <Route exact path="/Bookings" component={EnhancedBookingTable}/>
                        <Route component={Error}/>
                    </Switch>
                </Grid>
            </Grid>
        </Grid> 
    ):(
        <>
            <Redirect to="/login" />
            <Route exact path="/login" render={(props)=>(
                <Login {...props}
                    ID={ID}
                    setID={setID}
                    handleLogin={handleLogin}
                    IDError={IDError}
                    setIDError={setIDError}
                />
            )}/>
        </>
    )}
    </Router>
  );
}

export default App;

The Hardcoded auth is working fine. But there is only one problem, i.e., whenever the page is refreshed, the user gets logged out. This is because the setUser value is initialized to false on every re-ender. How to handle this??

1 Answers

React state exists only in memory, when you reload the page it is reset from scratch. You can use localStorage to persist your user state.

// state initializer function
const [user, setUser] = useState(() => {
  const loggedIn = localStorage.getItem("auth");
  return JSON.parse(loggedIn) ?? false;
});

// persist state to local storage on updates
useEffect(() => {
  localStorage.setItem("auth", JSON.stringify(user));
}, [user]);

Demo

Edit problem-in-implementing-hardcoded-auth-in-reactjs

Related