0

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 },
      ]);
    });
}
VersifiXion
  • 2,152
  • 5
  • 22
  • 40
  • Use an effect hook with `messages` as a dependency – Phil Jan 19 '23 at 00:18
  • 2
    but wouldn't I get an infinite loop ? messages is updated in ```addMessage``` and ```getResponse``` – VersifiXion Jan 19 '23 at 00:19
  • In that case you need two separate states – Phil Jan 19 '23 at 00:21
  • I'm displaying the conversation between me and chatGPT, using ```messages``` array on which I map to display the list of messages, I'll find a way.. – VersifiXion Jan 19 '23 at 00:24
  • 1
    Why do you want to wait before sending the async request? Presuming you're displaying `messages` on the screen, the re-render will happen faster than the network request, so the visual effect should be correct... Also, you should be using the callback version of `setState` since you're relying on the previous state. – gerrod Jan 19 '23 at 00:39
  • when the user sends his message, I want his message to be displayed directly, and then the request to the api is made and it gets the message from chatgpt – VersifiXion Jan 19 '23 at 00:43
  • But that's exactly what will happen... you don't need to wait for the re-render before you do the request. – gerrod Jan 19 '23 at 01:10
  • what happened with the code above is that my message appears and then is erased by the chatgpt message,only chatgpt messages remains in the UI, there's an issue with the many setState written in the same function – VersifiXion Jan 19 '23 at 11:06
  • Yep - here's an article that explains it - https://codegino.com/blog/react-setstate-callback-function – gerrod Jan 19 '23 at 21:42

1 Answers1

1

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]);
gerrod
  • 6,119
  • 6
  • 33
  • 45