fac-13 / KAEA

1 stars 0 forks source link

Mutation is a debuggers worst nightmare #17

Open akinsho opened 6 years ago

akinsho commented 6 years ago

Here you are very close to what looks like a contravention of sacred law, this sacred law in the land of react (think of it as the first commandment) is Never mutate state šŸ˜‰ or props you should always be v. wary of code that looks like

    thing1 = "apple"
    thing1 = randomOtherThing

// More scary is
    this.state.apple = "pear"

The reason mutation in this (and many other scenarios) is a big problem is that by reassigning state or mutating state you immediately lose the ability to track what things were. think of it a little like git history if you go back to a previous commit and say delete it or change what happened then your git history becomes hard to follow since there are missing bits, it becomes unclear what happened or how you even got there.

In the case above since what youre trying to do is increment the score by 10 and reassign current score to old score id suggest (you dont actually seem to be setting the oldscore in setState but relying on mutation but you create an new variable when you destructure so nothing happens?)

const { oldScore, score } = this.state
this.setState({ oldScore: score, score: score + 10 })
oliverjam commented 6 years ago

I was confused by this function as well. You don't actually have an oldScore key in your state, so the destructuring isn't doing anything. It would be a bit clearer if you made what you're doing explicit:

  score = () => {
    console.log('we have scored');
    const { score: oldScore } = this.state;
    this.setState({ score: oldScore + 10 });
  };