#Optimistic chat UI with Remix
1 messages · Page 1 of 1 (latest)
A way you could achieve this, load messages in your loader. have a state of optimistic messages that when you send immediately gets appended to, and when the fetcher.data comes back have it return the accepted value or an error if error plop your message back into the chat message box, otherwise you can clear the optimistic message state
if it's a real time chat, you probably want to reach for a websocket
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
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
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
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
You don’t need to key based on text
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