JavaScript React Components Managing State and Data Flow Adding Items to State

Yoan Herrera
Yoan Herrera
16,320 Points

is there a reason why we don't use preState inside the AddPlayerForm but we use it everywhere else in the app??

is there a reason why we don't use preState inside the AddPlayerForm but we use it everywhere else in the app??

Is it because we are not performing a calculation based on a previous state?

when is it ideal to use prevState and when is not??

thomas shellberg
thomas shellberg
6,359 Points

I was asking myself the same thing because we should be treating State is if it were immutable.

This might be ugly but it works for me:

handleAddPlayer = ( name) => {

    const newIndex = this.state.players.length +1;

    this.setState( prevState => {
      return {
        players: [ ...prevState.players,
          {
            name,
            score: 0,
            id: newIndex
          }
        ]
      };
    });
  }

1 Answer

Yoan Herrera
Yoan Herrera
16,320 Points

yes. I kept watching and saw that they fix it in the next video. i had a lot of troubles on Redux section. the course files have a lot of broken old dependencies. was hell to get it to work.