Reputation:
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
Reputation: 847
const [drawing, setDrawing] = useState(false)
const toggleDrawing = () => {
setDrawing(!drawing);
}
<button onClick={toggleDrawing}>Toggle Drawing</button>
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
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
Reputation: 4332
You're just returning the toggleDrawing
function without executing it
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