Home > Enterprise >  Update state for function that relies on if statement in ReactJs
Update state for function that relies on if statement in ReactJs

Time:08-13

Is it the best way to write the code below or i have to do better!

toggleListen() {
    if (recognition !== null) {
        this.setState({
            listening: !this.state.listening
        }, this.handleListen)
    } else {
        this.setState({
            microAvailable: !this.state.microAvailable
        }, this.handleListen)
    }
}

CodePudding user response:

Yes, you can conditionally set the listening or microAvailable properties depend on recognition !== null

function toggleListen() {
    this.setState(
        {
            ...(recognition !== null
                ? {
                      listening: !this.state.listening,
                  }
                : {
                      microAvailable: !this.state.microAvailable,
                  }),
        },
        this.handleListen
    );
}
  • Related