Home > database >  Syntax for Passing and Invoking Async Callbacks as a React Props
Syntax for Passing and Invoking Async Callbacks as a React Props

Time:11-01

I'm wondering what the right syntax is for passing, then invoking async calls through React components. Specifically:

Often, I'll have a function like this:

const doAsync = async (obj) => {
   await doSomethingAsync(obj)
}

...and then I'll pass it down to a Component like this:

<>
   <MyComponent asyncCallback={doAsync} />
</>

I'm a little confused about a couple of things here:

  1. Should I be passing the function down as asyncCallback={doAsync(obj)} or asyncCallback={async () => await doAsync(obj)} or just asyncCallback={doAsync}?
  2. When this function is invoked, in say a <button>, should it be done like this onClick={async (obj) => doAsync(obj)} or onClick={doAsync}?

Thanks for your help!

CodePudding user response:

Passing function like this asyncCallback={doAsync} is the best approach. You just pass this function as any other variable and this is ok.

Passing function like this asyncCallback={async () => await doAsync(obj)} also should work but it just to much boilerplate and you unnecessary make two new functions every rerender.

Passing it like this asyncCallback={doAsync(obj)} DOESN'T WORK because you dont pass this function you CALL IT in this place.

2. You can do it like this onClick={doAsync} but you will pass event variable as an argument not your custom obj (if it's ok you can do it like this).

If you want to pass you custom obj variable you can pass it like this onClick={() => doAsync(obj)} (you don't need to use async or await keyword).

  • Related