Home > Back-end >  Executing a function only after setState is done
Executing a function only after setState is done

Time:01-19

I'm using openAi API to talk to ChatGPT in my React App, I want to send the request to ChatGPT after my message is asynchronously added to messages array, Is there a way to do it ?

function addMessage() {
  setMessages([...messages, { writer: "Me", text: "Hi ChatGPT, how are you ?" }]);

  // execute this after the asynchronous setState above is over
  getResponse();
}

function getResponse() {
  getOpenAiCompletions(text, temp).then((response) => {
      setMessages([
        ...messages,
        { writer: "ChatGPT", text: response.data.choices[0].text },
      ]);
    });
}

CodePudding user response:

If you're just wanting the messages to appear in order, you don't need to wait for the re-render. Even if the response comes through instantly (which is very unlikely), the user's messages will still show before the response messages get appended to the array.

Here's a code sandbox that shows this in action.

Note that you should also be using the callback version of setMessages since you're relying on the previous state -

const addMessage = (msg: string) => setMessages((prev) => [...prev, msg]);
  • Related