0

I created a chatbot and want to initiate two Dialogflow API calls within a useEffect Hook. Function 1 and function 2 are both async api calls. The wanted result is that it first finishes function 1 and then starts with function 2, but currently function 2 returns the value faster than function 1.

Do you have any idea how I can tell function 2 to wait until function 1 returns a value?

useEffect(
    () => {
      createChatSessionId();
      fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId); // function 1
      fetchEventAnswerFromDialogflow("Frageevent1", chatId); // function 2
    }, // eslint-disable-next-line
    []
  );
Rainer Winkler
  • 485
  • 1
  • 7
  • 20
  • Can we use a callback in `fetchEventAnswerFromDialogflow` else you need to use `async -await` (its already there in one of the answers below) – kiranvj Aug 04 '20 at 05:52

1 Answers1

3

API Calls are asynchronous. When the compiler hits an async statement, it doesnt wait for it to finish, instead calls next statement.

Option one, (Using .then block) :-

  useEffect(
    () => {
      createChatSessionId();
      fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId).then(rep=>{
      fetchEventAnswerFromDialogflow("Frageevent1", chatId);})
        .catch(err){
          console.log(err)
         }
    }, // eslint-disable-next-line
    []
  );

Option two - As per ES6 using async await. I'd suggest not to make useEffect callback as async, instead make a new async function inside useEffect and call that.

useEffect(
    () => {
      createChatSessionId();
      const getData = async() =>{
         await fetchEventAnswerFromDialogflow("Startevent" + chatId, chatId);
         await fetchEventAnswerFromDialogflow("Frageevent1", chatId);  //Can remove await 
             //here, depending upon usecase
      }
      getData();
    }, // eslint-disable-next-line
    []
  );
  • 1
    If fetchEventAnswerFromDialogflow does not return a promise, making useEffect async and awaiting for the function wont do anything. Beside making useEffect async is not a proper thing to do [Here is why](https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret) – Robin Chauhan Aug 04 '20 at 06:09
  • Please check the stack forum. Link provided in previous comment – Robin Chauhan Aug 04 '20 at 06:14
  • thnx for the link – Apostolos Aug 04 '20 at 06:14
  • well, we learned sth new today! didnt know that about the async in `useEffect` so I need to change some forgotten parts of my code. I'll delete my answer since yours is correct. thnx again :) – Apostolos Aug 04 '20 at 06:31