FredrikOseberg / react-chatbot-kit

MIT License
297 stars 139 forks source link

How can I update the existing message? #132

Open bushev opened 1 year ago

bushev commented 1 year ago

Hi,

I am in the process of integrating this library with a WebSocket server that broadcasts messages partially. Consequently, whenever I receive an extension of a message (identified by a specific ID), it is necessary to update the corresponding message in the chat.

I previously attempted to substitute the entire message, but this occasionally caused the message to be divided into two to four separate segments.

image
sam-h-bean commented 1 year ago

Yeah would also like to use server sent events for this @FredrikOseberg

zoetaka38 commented 1 year ago

@bushev I was able to do this by doing the following:

messageBuffer += new TextDecoder("utf-8").decode(value)
var botMessage = createChatBotMessage(messageBuffer)

setState((prev: any) => {
  const prevMessagesWithoutLast = prev.messages.slice(0, -1)
  return {
    ...prev,
    messages: [...prevMessagesWithoutLast, botMessage],
  }
})

in my situation, i got the response as streaming response from fastapi (python).

OliverThomas2000 commented 5 months ago

Try this out:

const updateLastMessage = (message) => {
    setState((prev) => {
      return { ...prev, messages: [...prev.messages.slice(0, -1), { ...prev.messages.at(-1), message }]};
    });
  };