I'm building a chat app and I'm trying to add an optimistic response when user is sending a message. However, when combining optimisticResponse & update options of useMutation I came across an issue.
When I write the optimistic response payload to the cache using proxy.writeQuery (after merging it with previous content of the cache), the cache becomes empty until the actual Mutation response (and payload) is received by the client.
A little bit of info, the cache should be empty in the beginning since I haven't write any data into it (no db / backend is available yet). However, even after I wrote some data into it (data sent by user, is sent back to the client), proxy.readQuery still yields an empty cache before an actual Mutation response is received
Here's my mutation Hooks code
sendMessage({
variables: { message: messagePayload },
// set temporary message
optimisticResponse: {
sendMessage: {
...messagePayload,
message_id: randomID,
__typename: "message"
}
},
// Update local cache with new message
update: (proxy, { data: { sendMessage } }) => {
// Read the data from our cache for this query.
const existingData: any = proxy.readQuery({
query: getMessageListQuery,
variables: {
agentID: someID,
roomID: props.activeChat
}
});
// Push new data into previous data
existingData.messages.push(sendMessage)
// Write our data back to the cache with the new message in it
proxy.writeQuery({ query: getMessageListQuery, data: existingData })
// reading query here will yield an empty array
console.log(proxy.readQuery({
query: getMessageListQuery,
variables: {
agentID: someID,
roomID: props.activeChat
}
}))
}
})
From tutorials that I have seen, writing optimisticResponse payload & actual Mutation response payload should be the same and doesn't empties the cache.
Am I using it wrong or is this a bug?
Queries that share the same GraphQL document but have different variables are stored separately in the cache. After all, the result of the query will likely be different if the variables are different. That means when we both read from the cache and read to the cache (using readQuery
and writeQuery
respectively), we need to specify the variables used. In your code, writeQuery
omits the variables, so you're not writing to the cache entry as you're reading.