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
  • You're not calling the function Commented May 15, 2021 at 8:07
  • Where is console.log in your code? setDrawing runs asynchronously maybe that is why the state doesn't update Commented May 15, 2021 at 8:07
  • 1
    Your onClick returns the function instead of calling it. Either pass the function itself instead of the anonymous arrow function, or call the function instead of/when returning. Commented May 15, 2021 at 8:07

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

6 Comments

I did the same thing you explained, but it is not solved. here is my full code: codesandbox.io/embed/…
You cannot console.log in the toggleDrawing function react state is not updated if you call console.log outside of it will show true
I need to access the drawing variable and do something with it inside the function with the new updated value.
you can use useEffect for it
i will attach it in sanbox wait a minute
|
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>

2 Comments

I tried that but it doesn't work. here's my code: codesandbox.io/embed/…
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. @AymanTarig

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.