The Traveling Coder
The Traveling Coder

Reputation: 311

Pushing to array in React

so I have this website that randomly chooses a Pokemon from a large json file and returns the value to the user. There is a button the user can press to re-roll.

constructor(props) {
    super(props);
    this.state = {
      history: [],
      pokemon: []
    };
  }

spinAgain() {
    this.setState({history: this.state.pokemon})
    console.log(this.state.history);
    fetch('/api/pokemon')
      .then(res => res.json())
      .then(pokemon => this.setState({pokemon}, this.setState({history: pokemon}), () => console.log('Pokemon fetched...', pokemon)));
  }

render() {
    return (
      <div>
        <h2>Pokemon</h2>
        <ul>
        {this.state.pokemon.map(pokemon => 
          <li key={pokemon.id}>{pokemon.name} {pokemon.galar_dex}</li>
        )}
        </ul>

        <button onClick={() => this.spinAgain()}>Spin Again</button>
      </div>
    );
  }

What I have not been able to figure out is how to push the Pokemon to the history state instead of changing the state over and over.

Upvotes: 0

Views: 92

Answers (2)

lanxion
lanxion

Reputation: 1430

Expanding on @hellojeffhall's answer, what you need to do in your setState to push the current pokemon into the array is:

this.setState({
history: [...history, pokemon]
})

If the returned pokemon in the payload is also an array, and you need to push the entire array into your history state, then you can change it to

this.setState({
history: [...history, ...pokemon] //spread operator on both the arrays
})

Upvotes: 2

hellojeffhall
hellojeffhall

Reputation: 301

In general you should never directly mutate your state in React. If you need to add an item to an array in state, you should setState using a new array that includes the new item. For example:

this.setState({ myArray: [...this.state.myArray, myNewItem]})

Upvotes: 1

Related Questions