Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Syntax for Passing and Invoking Async Callbacks as a React Props

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<>
   <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!

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading