2

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);
  }
1
  • Tip: don't try to use a new state right after you used setState. The setState is asynchronous, if you want to use the new state, use the callback of setState. Just a complement to the answers below. Commented Dec 3, 2019 at 1:05

3 Answers 3

2

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
    }
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

I guess it would be better to use a callback in this case
Thanks a bunch!!! I was able to put my markers down on Google Maps correctly.
1

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,
   },
});

Comments

0

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 } }))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.