简体   繁体   中英

Executing a function only after setState is done

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 },
      ]);
    });
}

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM