I am using useState for this object 'selected', i want to get the updated value in this function verifyActive
const [selected, setSelected] = useState({ a: '', b: '' })
and i have a function that is active since a button
const setActive = (value) => {
setSelected({ ...selected, b: value })
verifyActive()
}
const verifyActive=()=>{
console.log('selected', selected) // is not updated
}
...
console.log(selected) //here is value is updated
return (
<button
onchange={(value) => { setActive(value) }}
/>
CodePudding user response:
change your setActive to this way
const setActive = (value) => {
setSelected((prevSelected) => { ...prevSelected, b: value })
verifyActive()
}
CodePudding user response:
The local const selected
is never going to change, but what you can do is save the new state to a variable, and pass it in to verifyActive:
const setActive = (value) => {
const newState = { ...selected, b: value };
setSelected(newState);
verifyActive(newState);
}
const verifyActive = (value) => {
console.log('selected', value);
}