Search code examples
javascriptreactjssetstate

How does setState in React work in this scenario?


I'm trying to set the state of an object inside my array. I have achieved it but I don't understand it.

toggleVisited = countryCode => {
  var countries = [ ...this.state.countries ];
  var countryToChange = countries.find(country => country.code === countryCode);
  countryToChange.visited = !countryToChange.visited;
  this.setState({ countryToChange });
}

I understand (mainly) what is happening, up to the last this.setState line.

I changed the code to this.setState({}) and it still worked. I always thought set state was setting the new value for an object key. Why (no matter what I put in here), is it still setting it correctly?


Solution

  • With countryToChange.visited = !countryToChange.visited, you are mutating your current state. Don't do this. Create a new object instead:

    toggleVisited = countryCode => {
        this.setState(prevState => {
            const countries = prevState.countries.map(country => country.code !== countryCode
                ? country
                : {
                    ...country,
                    visited: !country.visited
                })
            const countryToChange = countries.find(country => country.code === countryCode)
    
            return {
                countries,
                countryToChange
            }
        })
    }