ylvare / jammming

Codedamy project
0 stars 0 forks source link

Avoid Mutating State Directly #1

Open tbergen1 opened 6 years ago

tbergen1 commented 6 years ago

In React, mutating state should be avoided at all costs. I noticed that in your addToPlaylist function in App.js, you are mutating state directly by pushing into an array contained within state. You can view the function here:

https://github.com/ylvare/jammming/blob/3cf516d2754e8dbcab99ecad288bdc02787dabb2/src/App.js#L55-L61

You should always use "setState" to update state. To avoid what you did above, you should create a copy of the array, mutate the copy, then update state with "setState." This would look like the following:

addToPlayList(track){
   const newSearchResult = this.state.searchResult.filter(e => e !== track)
   let playlist = [ ...this.state.playlist, track ];
   this.setState({
     searchResult: newSearchResult,
     playlist
   });
}
ylvare commented 6 years ago

Ah. I dont really understand "let playlist = [ ...this.state.playlist, track ];" but I will google it!! I will not update the states from other place than within setState. Got the message :)

tbergen1 commented 6 years ago

"let playlist = [ ...this.state.playlist, track ];" is ES6 syntax. It leverages the spread operator, which is the "...". Essentially what it does is causes the playlist array to "spread" and have each of its elements copied into the array containing it. The new track is then added as a separate element on the end of that new array.

If the playlist array is [track1, track2, track3], the spread operator will take each element and put it into the empty array, resulting in this:

[track1, track2, track3, track]