Reputation: 113
I'm am using React to set the visbility (isMarkerShown) of a marker when I click a menu item which is handle by my handleMarker(). I get an undefined value if I tried to set the state like how I did below.
state = {
collapsed: false,
visible: false,
marker: {
isMarkerShown: false,
lat: 0,
lng: 0,
},
};
handleMarker() {
this.setState({marker: this.setState({isMarkerShown: true})});
console.log(this.state.marker);
}
Upvotes: 2
Views: 90
Reputation: 650
If you need to access value of current/previous state while setting state- like toggling on/off- you can access it directly within the setState call. You can also use functional setState to ensure your state updates happen in order:
this.setState(prevState => ({ marker: { ...prevState.marker, isMarkerShown: !prevState.marker.isMarkerShown } }))
Upvotes: 0
Reputation: 16576
It looks like you might be trying to maintain the rest of the marker props while changing isMarkerShown
. If that's the case, the following approach may help:
handleMarker() {
this.setState({
marker: {
...this.state.marker,
isMarkerShown: true
}
});
}
Upvotes: 2
Reputation: 41893
setState
function is a void
function - it does not return anything. So actually if you are assigning it to some variable, it will hold an undefined
value.
Just try to set the state directly:
this.setState((prevState) => ({
marker: {
...prevState.marker,
isMarkerShown: true,
},
});
Upvotes: 1