Hi. I’m trying to add optimistic response to a mutation sendMessage
. In terms of business logic, this mutation adds a new message to a chat channel. I’m encountering a bug where if I send messages “1” “2” “3” in rapid succession on an artificially throttled network, I’ll see:
duplicate.mov - Google Drive (screen recording)
I’ve consulted these docs:
https://www.apollographql.com/docs/react/performance/optimistic-ui
https://www.apollographql.com/docs/react/caching/cache-interaction
https://www.apollographql.com/docs/react/data/mutations#updating-the-cache-directly
My code is something like:
const content = /* get content from input field */
/* clear input field so user can immediately start typing another message */
const temporaryId = `temp-id-${Date.now()}`;
const optimisticResponse = {
sendMessage: {
__typename: "Message" as const,
id: temporaryId,
content,
...
}
}
await sendMessage({
variables: {...},
optimisticResponse,
update: (cache, { data: { sendMessage: newMessage } }) => {
... /* I've tried various approaches here */
}
});
The UI renders messages that are nested in the results of another query, channelById
, which returns a Channel
type.
My understanding is:
- Since I’ve specified
optimisticResponse
, the Apollo client will immediately add the optimistic message to the cache once the mutation is triggered. - The
messages
list deep inside thechannelById
result may not necessarily be automatically updated, so I would have to manually define how to update that part of the cache by writing anupdate
function. In practice, it seems thatmessages
does update automatically, and theupdate
function isn’t needed?
I’ve tried passing several different update
functions into the mutation (including no function) and they all lead to this behavior.
Does anyone know how to fix this?