user14483466
user14483466

Reputation:

React setState doesn't update boolean variable

I created a state variable using

const [drawing, setDrawing] = useState(false)

Then I've this button which should update the value of drawing

 <button onClick={() => toggleDrawing}>Toggle Drawing</button>

The toggleDrawing function is:

const toggleDrawing = () => {
    setDrawing(true)
  }

but when I press the button and console.log the value of drawing id doesn't update, it's always a step behind. it start with a value of false, after one click it remains false and after the second click it switches to true.

Upvotes: 0

Views: 3560

Answers (3)

Arihant Jain
Arihant Jain

Reputation: 847

const [drawing, setDrawing] = useState(false)

Case:1 If you want a toggle true=>false and false=>true

const toggleDrawing = () => {
    setDrawing(!drawing);
  }

<button onClick={toggleDrawing}>Toggle Drawing</button>

Case:2 If you just want to set it to true

 const toggleDrawing = () => {
    setDrawing(true);
  }

<button onClick={toggleDrawing}>Toggle Drawing</button>

Sandbox https://codesandbox.io/s/vigilant-meadow-thdni?file=/src/App.js

Note => console.log(drawing) in toggleDrawing function will return false at first then true reason is state is not updated

Upvotes: 0

PixAff
PixAff

Reputation: 329

const toggleDrawing = () => {
    setDrawing((oldValue) => !oldValue)
  }

if you want to toggle state in React you always want to refer to the previous state

Upvotes: 1

fortunee
fortunee

Reputation: 4332

The Problem

You're just returning the toggleDrawing function without executing it

Solution

Execute the function when the click event occurs like this

<button onClick={() => toggleDrawing()}>Toggle Drawing</button>

Or pass the toggleDrawing to onClick as the actual function like

<button onClick={toggleDrawing}>Toggle Drawing</button>

Upvotes: 0

Related Questions