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:
Screen recording optimistic mutation duplicate messages.mov - Google Drive (screen recording)
I’ve consulted these docs:
https://www.apollographql.com/docs/react/performance/optimistic-uihttps://www.apollographql.com/docs/react/caching/cache-interactionhttps://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
messageslist deep inside thechannelByIdresult may not necessarily be automatically updated, so I would have to manually define how to update that part of the cache by writing anupdatefunction. In practice, it seems thatmessagesdoes update automatically, and theupdatefunction 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?