Search code examples
javascriptreactjsobjectfetchstate

How to change object's attribute in React


I want to change the "height" value of the object "pokemon"

state = {
    loaded: true,
    error: false,
    pokemon: {
        id: this.props.number,
        number: this.props.number,
        name: this.props.name,
        height: 188,
    }
}

But when I try Prevstate it doesn't work:

        axios.get('https://pokeapi.co/api/v2/pokemon/' + this.state.pokemon.number)
        .then(response =>{
            this.setState(prevState =>({
                pokemon: {
                    ...prevState.pokemon,
                    height: response.height
                }
            }))
        })

Solution

  • I think you are missing the .data after response.

    pokemon: {
      ...prevState.pokemon,
      height: response.data.height
    }