Search code examples
javascriptreactjstypescriptecmascript-6setstate

How to update the state to its previous state in React + Typescript


I want to set the state to its previous value. I have a list of checkboxes and based on it selections and click of "Apply" the columns in the table gets shown/hidden. I am able to achieve this functionality. But on click on "Cancel" , I am not able to set it to previous state.

CodeSandbox: https://codesandbox.io/s/funny-browser-2z3s5

On click of Cancel, the checkboxes should be set to previous state.

Click is handled with a function in SelectComponent.tsx, the goal is to reset optionsArr to its original value:

cancelSelection = (event: any) => {
  this.setState({ showList: false });
  this.setState((prevState: any) => ({
    // Isn't working
    optionsArr: prevState.optionsArr
  }));
};

Solution

  • The argument that setState updater gets is state at the time the change is being applied. Setting state equal to that changes nothing.

    You need to keep track of previous state separately. For example as separate item in the state, an instance variable or the props. See for example:

    Reset initial state in React + ES6

    Clearing state es6 React