liftedpixel / jammming

a Codecademy React project
http://jammmmmmmmmmmming.surge.sh
0 stars 0 forks source link

Avoid writing to state #4

Open ghost opened 6 years ago

ghost commented 6 years ago

https://github.com/liftedpixel/jammming/blob/master/src/components/App/App.js#L20-L21

When you write something like

let someArray = this.state.someProperty;
someArray.push();

You are directly mutating React's state. This is a bad practice, as React's state should only be changed by this.setState(). Consider using a non-mutating Array method instead, like slice, concat, map, or filter which returns a brand new array instead.

You are then free to mutate that copied array and then pass the final version to this.setState().

let updatedPlaylistTracks = this.state.playlistTracks.concat(track);
this.setState({
  playlistTracks: updatedPlaylistTracks
});