Morning.
I have a silly looking problem with setting new value with conditional operator. Below is a hugely simplified code block, that is meant to switch value of 'selectedDc' from 0 to 1 or vice versa, and after that it gets new values from server with the changed value. However the new value of 'selectedDc' is not there instantly as the code reaches API calling rows, so the calls are made with old value. This causes the program to run 'one click behind' the users intentions.
import React, {useState} from 'react';
const App = () => {
const [selectedDc, setDc] = useState(0)
//event triggered by pressing button
const handleDcChange = async (event) => {
event.preventDefault()
console.log(selectedDc) //prints 0 as expected
const dcValue = (selectedDc === 0) ? 1 : 0
console.log(dcValue) //prints 1 as expected
setDc(dcValue)
console.log(selectedDc) //still after setting new value, prints 0??
//Following lines are just several api calls that work as intended, no need to show implementation.
await daycareService.changeDc(selectedDc)
setShifts(await shiftService.getAll())
setDcTeams(await daycareService.getGroups(selectedDc))
}
}
I first tried to set new value without creating new const first, but it worked exactly the same way, one step behind.
selectedDc === 0 ?
setDc(1) :
setDc(0)
What am I doing wrong, what should I do to get the correct output with the first trigger?