-1

The below function logic works, but reading through various posts and SO questions, learned that this should be avoided. So, I'm trying to use callback in setState to reference the previous state. saveOptions function call is dependent on the state change.

Converted the below code

validateOnSave() {
    const copy = this.state.codeSelectionIsInvalid;
    copy[0] = !this.state.reasonCode;
    copy[1] = !this.state.remarkCode;
    copy[2] = !this.state.otherCode;
    this.setState({ codeSelectionIsInvalid: copy });

   if (!copy[0] && !copy[1] && !copy[2]) {
      this.saveOptions();
    }
  }

To use callback

validateOnSave() {
    this.setState(prevState => ({
      codeSelectionIsInvalid: [!prevState.reasonCode, !prevState.remarkCode, !prevState.otherCode],
      },
      () => {
        if(!prevState.reasonCode && !prevState.remarkCode && !prevState.otherCode) {
          this.saveOptions();
        }
      }
    )
}

Error:

{ SyntaxError: OptionsView.jsx: Unexpected token, expected "," (110:2)

  108 |       }
  109 |     )
> 110 |   }

But this is not quite working. Giving me syntax errors. Where am I going wrong here? Thanks for the help!

babybear
  • 804
  • 1
  • 10
  • 24

1 Answers1

1

On the first callback, you are forgetting the close ) to complete the shorthand arrow function i.e.

prevState => ({
  codeSelectionIsInvalid: [!prevState.reasonCode, !prevState.remarkCode, !prevState.otherCode],
}), // <-- closing bracket
() => { ...
James
  • 80,725
  • 18
  • 167
  • 237
  • If I put the closing bracket there, I'm not able to use prevState in the callback function. Is there any way to do that? – babybear Mar 02 '20 at 01:54
  • 1
    @Vidhi is it really the previous state you are after or is it the updated state? If so, you can simply use `this.state` – James Mar 02 '20 at 06:51