0

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
  }));
};
2
  • 1
    I voted to close because it relies on third-party content (codesandbox) that is subject to change/removal. If this happens, this question will not make sense, thereby eliminating any usefulness to future users. It also means that there are minimal code-related search terms in you question, reducing the ability of search engines to index your question. Please present your code using the tools provided by SO, considering this and this for guidance. Commented Jun 26, 2019 at 10:39
  • meta.stackoverflow.com/questions/377959/… Commented Jun 26, 2019 at 10:46

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.