0

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.

1
  • But then, if you done yoint to change the state, rerendering will not happen and you will not see the new content on UI Commented Sep 16, 2020 at 3:46

2 Answers 2

2

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

Comments

1

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

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.