Home > Mobile >  Async/Await function gets called twice
Async/Await function gets called twice

Time:04-14

I made a simple Async function and wanted to test run it in my react app. The function is:

async function WAIT(time: any) {
  await new Promise((r) => setTimeout(r, time))
}

export async function GetMemberList(orgId: string):Promise<ResponseInterface>{
  await WAIT(3000);
  return {code: 404, data: "Data"}
} 

And i try to call it in my main app like this:

function App() {
  async function fn() {
    let x = await GetMemberList('SOme');
    console.log(x);
  }
  fn();
  return (<div>.....<div>)
}

But the problem is console.log(x) runs twice. I get {code: 404, data: "Data"} twice. Why is that? Thanks

CodePudding user response:

I tried running your code and it's outputting once.

Most probably, the problem is that something is triggering a rerender in your template and the fn() is getting called again.

You can easily verify it by wrapping your fn() inside of a useEffect().

CodePudding user response:

Here's the solution:

function App() {
  async function fn() {
    let x = await GetMemberList('SOme');
    console.log(x);
  }

  React.useEffect(() => {
    fn();
  }, []);

  return (<div>.....<div>)
}

Making use of useEffect with an empty dependency array will make it so that the fn() only gets called once upon the App component mounting.

  • Related