1

Simple question, I am sure that I am being stupid and it is an easy fix. Have an array of objects and want to access each object's vis value and change it through my for loop. I don't understand why it doesn't work.

onSearch = keyWord => {
    let newMarkers = this.state.markers;
    for (let i = 0; i<this.state.markers.length;i++) {
      if (this.state.markers[i].name.toLowerCase().includes(keyWord.toLowerCase())) {
        newMarkers[i].vis = true;
      } else {
        newMarkers[i].vis = false;
      }
    }
    console.log(newMarkers);
    //console.log to see if the vis value has been changed: spoiler alert it hasn't :(
    this.setState({markers: newMarkers});

    console.log(this.state.markers)
  }
4
  • 2
    Console.log will never show the change to you since setState is async operation. Commented Jun 24, 2020 at 3:18
  • my newMarkers isn't changed either though and it doesn't use setState? Commented Jun 24, 2020 at 3:24
  • I had a typo from fiddling with it too much, it works now. Thank you for your help! Commented Jun 24, 2020 at 3:31
  • 1
    Good to hear you found out the issue. Happy Learning! Commented Jun 24, 2020 at 3:33

2 Answers 2

3

setState is asynchronous. Therefore you need to write the code as follows:

onSearch = keyWord => {
  let newMarkers = this.state.markers;
  for (let i = 0; i<this.state.markers.length;i++) {
    if (this.state.markers[i].name.toLowerCase().includes(keyWord.toLowerCase())) {
      newMarkers[i].vis = true;
    } else {
      newMarkers[i].vis = false;
    }
  }
  console.log(newMarkers);
  this.setState({markers: newMarkers}, () => {
    // use this callback function to do stuff AFTER state changes
    console.log(this.state.markers);
  });
}
Sign up to request clarification or add additional context in comments.

2 Comments

I see, I will keep this in mind in the future, thank you!
@ZKJ this is the better answer, as it makes use of the intended API for setState as opposed to a hacky way of stein gifting/parsing data to make a copy.
2

It keeps the state unchanged in your case. To overcome you might adapt a quick fix to this. Follow the code.

const jsonNewMarkers = JSON.stringify(newMarkers);
this.setState({markers: JSON.parse(jsonNewMarkers)}, () => {
  // use this callback function to do stuff AFTER state changes
  console.log(this.state.markers);
});

And please try the solution and let me know. It should work as mine it works.

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.