0

import React from 'react';

import {Redirect} from 'react-router-dom';

const SignIn = ()=>{

const [name , setName] = React.useState('');
const [password, setPassword] = React.useState('');
const [isLogged , setLog] = React.useState(false);
 const submit = () =>
 {
    localStorage.setItem('name','Faateh');
    localStorage.setItem('password','Pass')
    if(name === localStorage.getItem('name') && password === localStorage.getItem('password'))
    {
        setLog(true);
        alert(isLogged);
    }
}

return(
    <div>
        <form>
            <label>Enter your name: </label>
            <input type="text" name = "username" value ={name} onChange = {e=> {setName(e.target.value)}} />
            <br />
            <label>Enter your password: </label>
            <input type="text" name = "password" value ={password} onChange = {e=>{setPassword(e.target.value)}} />
            <br />
            <button onClick = {submit}>submit</button>
        </form>
    </div>
)

} export default SignIn;

  • `isLogged` is a `const`. `const`'s don't change, that's their whole deal. Just because its a state variable doesn't mean it abides by different rules. It **will not change**; ever. What happens is you call the state updater and the **next render** (the `SignIn` function is called again) you will get a completely *new* `const` also called `isLogged` that holds the "updated" value. But you **will never** see the value updated during the same render. – Brian Thompson Jun 25 '21 at 20:53

1 Answers1

1

useState hook is asynchronous, and will not be reflected immediately.

setLog(true);
alert(isLogged); //won't alert the new value

And if you want to get the updated state value then use useEffect hook with dependency array. React will execute this hook after each state update.

setLog(current => !current); //you have already defined the initial value as false, so we can just change it like this since it's a boolean

useEffect(() => {
    alert(isLogged);
}, [isLogged]);

Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26