Setting the state and the function which is updating the state:
const [objectivesOpen, setObjectivesOpen] = useState([]);
const toggleObjectives = () => {
console.log('objectivesOpenNotUpdated', objectivesOpen);
setObjectivesOpen([Math.random()]);
}
Calling the function:
<button onClick={toggleObjectives}>Test</button>
objectivesOpen is not getting the updated value after clicking the button the next time.
UPDATE: The value is updated in useEffect(), but not when clicking the button.
useEffect(() => {
console.log('objectivesOpen in effect', objectivesOpen);
});
const toggleObjectives = () => {
console.log('time:', new Date())
console.log('objectivesOpen', objectivesOpen);
setObjectivesOpen([Math.random()]);
};
Results:
time: Thu Dec 03 2020 17:17:58 GMT+0100 (Central European Standard Time)
objectivesOpen [0.4735904311779686]
objectivesOpen in effect [0.12100479433701583]
time: Thu Dec 03 2020 17:18:01 GMT+0100 (Central European Standard Time)
objectivesOpen [0.4735904311779686]
objectivesOpen in effect [0.6376121961469396]