What is happening
The initial state is:
{button1:false,button2:false}
Then (via changeItem
) you call setClick(!Click.button1)
which sets a new state (false
because !any_object
is false
).
Then you call console.log(Click.button1)
which logs false
because the initial state's button1
property is false
.
Then a re-render is triggered which creates a new Click
variable containing the new state and a new changeItem
function which closes over the new Click
variable.
Next time you call changeItem
again and:
setClick(!Click.button1)
Click
is false
so Click.button1
is undefined
so you set the state to true
.
Then console.log(Click.button1)
logs the previously closed over Click
's (false
) button1
property which is undefined
because booleans don't have those properties.
How to update a property of an object in the state
You need to assign a new object to the state in which you only change the value you care about:
setState({
...Click, // Shallow copy all the old values
button1: !Click.button1, // Change the one you care about
})
How to observe the change
Use a useEffect
hook to log the value when the state changes:
useEffect( () => { console.log(Click); }, [Click] )
A note about style
By convention, variable names starting with capital letters are reserved for constructor functions and classes. Don't use them to store data. Call it click
.