1

I usually take care of any promises or asynchronous operations in the componentDidMount or componentWillMount lifecycle methods, but now I am using only functional components.

So I have something like this:

export async function MyComponent () {
  const data = await myPromiseFunction()

  return (
    <>
      DO SOMETHING!
    </>
  )
}

This obviously cannot be done because we are returning a promise when using MyComponent. So my question becomes how can I do asynchronous operations within the functional component?

Do I just have to accept that they have to be done elsewhere and receive my necessary data as props? Or is there a cleaner way to get around this?

theJuls
  • 6,788
  • 14
  • 73
  • 160

1 Answers1

2

you need Hooks; namely Effects hook.

there you can send http request within useEffect(() =>{ callMyApi()}) block.

you can see an example here: React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

dee zg
  • 13,793
  • 10
  • 42
  • 82