Apollo的proxy.writeQuery清空了缓存(错误与否?



我正在构建一个聊天应用程序,我正在尝试在用户发送消息时添加乐观的响应。但是,当结合useMutation的乐观响应和更新选项时,我遇到了一个问题。

当我使用 proxy.writeQuery 将乐观响应有效负载写入缓存时(将其与缓存的先前内容合并后(,缓存变为空,直到客户端收到实际的突变响应(和有效负载(。

一点信息,缓存一开始应该是空的,因为我还没有将任何数据写入其中(还没有可用的数据库/后端(。但是,即使我将一些数据写入其中(用户发送的数据被发送回客户端(,proxy.readQuery在收到实际的突变响应之前仍然会产生一个空缓存

。这是我的突变钩子代码

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 
} 
}))
}
})

从我看到的教程中,编写乐观响应有效负载和实际的突变响应有效负载应该是相同的,并且不会清空缓存。

我用错了还是这是一个错误?

共享同一 GraphQL 文档但具有不同变量的查询单独存储在缓存中。毕竟,如果变量不同,查询的结果可能会有所不同。这意味着当我们从缓存读取和读取缓存(分别使用readQuerywriteQuery(时,我们需要指定使用的变量。在代码中,writeQuery省略变量,因此在读取时不会写入缓存条目。

最新更新