-1
  useEffect(() => {
    if (names.length !== 0) {
      createName(id);
    }
    getName(id);
  }, [names]);

Here both the function createName and getName is a api call that returns a promise.

Now Sometime, createName delays which is causing getName to execute without a data.

So, how to make this usEffect async using async await ?

Sai Krishnadas
  • 2,863
  • 9
  • 36
  • 69
  • 2
    Does this answer your question? [How to call an async function inside a UseEffect() in React?](https://stackoverflow.com/questions/56838392/how-to-call-an-async-function-inside-a-useeffect-in-react) – marius florescu Sep 04 '21 at 13:32

1 Answers1

5

Just create an async function in useEffect and call it after:

useEffect(() => {
  const asyncFn = async () => {
    if (names.length !== 0) {
      await createName(id);
    }
    getName(id);
  };

  asyncFn();
}, [names]);
Viet
  • 12,133
  • 2
  • 15
  • 21