Search code examples
reactjssetstate

using update immutablity helper I get eslint error : Use callback in setState when referencing the previous state


Thanks in advance. I use immutability - helper to set the state. But i get eslint error near this.setState It says : Use callback in setState when referencing the previous state Is there any work around since i use immutablity helper do i need to use prevState Can any share corrected methods.

import update from 'immutability-helper';

moveSection = (dragIndex, hoverIndex) => {
    const { list} = this.state;
    const dragCard = list[dragIndex];

    this.setState(
      update(this.state, {
        list: {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragCard],
          ],
        },
      }),
    ); };

Solution

  • Try this:

    this.setState(
      (state) => {
         return update(state, {
           list: {
             $splice: [
               [dragIndex, 1],
               [hoverIndex, 0, dragCard],
             ],
           },
         })
      }
    );