#Optimistic chat UI with Remix

1 messages · Page 1 of 1 (latest)

tough falcon
#

I am trying to build a chat page with Remix. What I want is when the user enters a message and clicks send, the user message should be appended to the chat window immediately and then action be invoked which generates the response and sends it back

lapis token
#

if it's a real time chat, you probably want to reach for a websocket

tough falcon
#

i tried something similar..

#

my loader returns the last N messages.

#

and then i do const [messages , setMessages] = useState(loadedMessages)..

#

when user enters a new message and hits enter, i do setMessages([...messages, userEnteredMessage]) and then i invoke fetcher.submit() ..

#

where i am having trouble is the next part. the action does a redirect to the same page. i could send the generated response message as well. but how do i merge this with my local state? i don't know about any onFetcherFinish hook

lapis token
#

I think that usage of a state for the whole array of messages is a mistake

#

it should be a single state for a single string for one optimistic message

#

and you should clear that optimistic message state when the fetcher says things are good

#

by using a useState you make your loader data not actually sync the data

#

one of the ways i do a sort of fetcher finish, track previous fetcher state, when fetcher state goes from submitting to idle then i know something new has happened

winter dove
#

You can usually just get away with filtering the combined array to remove duplicates

#

Server data plus optimistic data

#

It’ll naturally clear on navigation

lapis token
#

Definitely can work, but it can be more complicated to do that depending on the chat setup. Imagine the user actually did have a duplicate message in the chat like:
user1: Do you want pie?
user2: No thanks
user1: How about some ice cream?
user2: No thanks

I mean, its unlikely and not a great example, but that sort of idea lol

winter dove
#

You don’t need to key based on text

lapis token
#

true, ID's, I was assuming the most basic structure of text messages, but if they end up in a db theres certainly an id