Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async/await in event handler in react

How can I use async/await in an event handler in react?

I understand the following code is wrong because I'm accessing this.state to get the customer code.

<button onClick={handleClick}>Get Customer</button>
async handleClick() {
    let customerCode = this.state.customerCode;
    let customer = await this.service.getCustomer(customerCode);
    this.setState({ customer });
}

Maybe it should be something like this, but I don't think this would work:

handleClick() {
    this.setState(async (prevState) => {
        let customerCode = prevState.customerCode;
        let customer = await this.service.getCustomer(customerCode);
        return { ...prevState, customer };
    }); 
}
like image 921
rm5432 Avatar asked Sep 18 '25 08:09

rm5432


1 Answers

I understand the following code is wrong because I'm accessing this.state to get the customer code

What makes you think it is wrong? It seems legit to me.
If you update a value in state like that (mutation) then it may consider as anti pattern, but reading values that way is perfectly fine.

With that said, i prefer to destruct the properties from the state or any other object in the top of the function's body:

async handleClick() {
  const { customerCode } = this.state;
  let customer = await this.service.getCustomer(customerCode);
  this.setState({ customer });
}

I think it's more readable, but both ways will work fine.

Edit

Just to clarify, when i wrote both ways will work fine, I meant with and without destructuring. e.g the OP first example and my example.

As for this comment:

this.state could be stale

In your case it doesn't matter. The only time an updater argument is required for setState is when the next state is depended on previous state, which is not the case here.

like image 133
Sagiv b.g Avatar answered Sep 20 '25 22:09

Sagiv b.g