Tuzi
Tuzi

Reputation: 160

Why do I have to click twice for an event in react js

var [broj, setBroj] = useState(0);
function plus() {
    setBroj(broj++)
}
function minus() {
    setBroj(broj--)
}
return (<div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
</div>
)

when i click first time nothing just after second time work every 2 time ( onclick ) work

Upvotes: 1

Views: 2331

Answers (3)

geoffrey
geoffrey

Reputation: 2444

This is because you post-increment and post-decrement.

Write setBroj(broj + 1) and setBroj(broj - 1)

Now you could pre-increment and pre-decrement but please don't. You don't need to mutate that variable.

Upvotes: 1

Lakshya Thakur
Lakshya Thakur

Reputation: 8316

That's because you're updating state the wrong way. You're mutating the state directly using ++ and -- operators which you shouldn't. Following is the correct way :-

var [broj, setBroj] = useState(0);
function plus() {
    setBroj(broj=>broj+1)
    //setBroj(broj+1) - this will also work.
}
function minus() {
    setBroj(broj=>broj-1)
   //setBroj(broj-1) - this will also work.
}
return (<div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
</div>
)

Upvotes: 3

michael
michael

Reputation: 4173

When you set the state value with setBroj(broj++) it doesn't change the state with broj + 1 value because ++ affects after the code is executed. You should use setBroj(broj + 1) instead.

var [broj, setBroj] = useState(0);
function plus() {
  setBroj(broj + 1);
}
function minus() {
  setBroj(broj - 1);
}
return (
  <div>
    <button onClick={plus}>+</button>
    <h3>{broj}</h3>
    <button onClick={minus}>-</button>
  </div>
);

Upvotes: 5

Related Questions