0

For this piece of code, !this.state.dark I am getting an ESlint (airbnb config) error:

Use callback in setState when referencing the previous state.

I tried refactoring the code using following the ESlint documentation. But I'm having a hard time figuring it out. Any suggestions on how I can solve this problem?

toggleDark = () => {
  const dark = !this.state.dark
  localStorage.setItem('dark', JSON.stringify(dark))
  this.setState({ dark })
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

Thanks to @jonrsharpe for pointing me to appropriate documentation.

It turns out that state updates may be asynchronous. React may batch multiple setState() calls into a single update for performance. In the came of my code, I only have one value that was being updated. But, it's still a good idea to use a second form of setState that accepts a function rather then an object.

toggleDark = () => {
  const dark = !this.state.dark
  localStorage.setItem('dark', JSON.stringify(dark))

  this.setState(({ dark }) => ({ dark: !dark }))
}
  • I would suggest you to call `setItem` inside your `setState` call back. – junwen-k Nov 23 '19 at 11:33
  • Interesting approach. How would the work? Something like this `this.setState(({ dark, setIteam }) => ({ dark: !dark }))`? –  Nov 25 '19 at 05:48
  • `this.setState(({ dark }) => { localStorage.setItem('dark', JSON.stringify(!dark)); return { dark: !dark }; });` – junwen-k Nov 25 '19 at 07:21