'Losing state inside eventHandler

const [page,setPage] = useState()

console.log(page) // gives "Page1" upon state update
const onValueChange = (event) => {
    console.log(page); //gives undefined upon state update
};

<Input
onChange={(e) => onValueChange(e)}         
/>

<SelectDropdown
onChange={() => setPage("Page1")}
value={page}
/>

Above code is a brief example on how I cant access the state "page" inside the function from an eventHandler, how is it possible to access the state inside onValueChange().



Solution 1:[1]

Your could should work as it is normally. An explanation of why you getting undefined in onValueChange is that you are changing the value of the Input before changing SelectDropdown's value, in witch case it's normal, because this line :

const [page,setPage] = useState()

sets page to undifined. You can test it here on this CodeSandbox I just created.

Solution 2:[2]

Change setStorageId to setPage in your SelectDropDown component

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Chigozie Ijomah