0

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.

3 Answers3

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

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

PixAff
  • 309
  • 4
  • 14
0
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

Arihant Jain
  • 817
  • 5
  • 17
0

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>
fortunee
  • 3,852
  • 2
  • 17
  • 29
  • I tried that but it doesn't work. here's my code: https://codesandbox.io/embed/misty-night-dm66l?fontsize=14&hidenavigation=1&theme=dark –  May 15 '21 at 08:29
  • It's actually working. The thing is, you're trying to access `drawing` immediately after you set it but you can't because [React setter hooks method is asynchronous](https://stackoverflow.com/questions/54119678/is-usestate-synchronous). @AymanTarig – fortunee May 15 '21 at 08:34