Search code examples
javascriptreactjseslinteslint-config-airbnb

Prevent using this.state within a this.setState (react/no-access-state-in-setstate)


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 })
}

Solution

  • 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 }))
    }