Ad

React Counter Hook Doesn't Increment

- 1 answer

When I click button which run function login first time hooks(state) logged has value 0 . I wish it had value 1

const [logged, setLogged] = React.useState(0);
const login = () => {
   if (tempLogin.login === "Login" && tempLogin.password == "Haslo") {
    setLogged(logged => logged + 1);
     console.log(logged);
  }
Ad

Answer

You're updating it right! Just logging in the wrong place, remember, hooks values gets updated on the next render and you're calling console.log inside login by the time login gets executed logged isn't updated yet

const Component = () =>{

    const [logged, setLogged] = React.useState(0);

    const login = () => {
         if (tempLogin.login === "Login" && tempLogin.password == "Haslo") {
             setLogged(logged => logged + 1);
     }
     //Component's body
     console.log(logged)  // 0, 1
     return <div>{logged}</div>
 }
Ad
source: stackoverflow.com
Ad