【发布时间】:2020-01-14 22:56:06
【问题描述】:
我正在构建一个聊天应用程序,并尝试在用户发送消息时添加一个乐观的响应。但是,当结合 useMutation 的乐观响应和更新选项时,我遇到了一个问题。
当我使用 proxy.writeQuery 将乐观响应负载写入缓存(在将其与缓存的先前内容合并后)时,缓存变为空,直到客户端收到实际的 Mutation 响应(和负载)。
一点信息,缓存一开始应该是空的,因为我还没有向其中写入任何数据(还没有可用的数据库/后端)。但是,即使我在其中写入了一些数据(用户发送的数据,被发送回客户端),proxy.readQuery 在收到实际的 Mutation 响应之前仍然会产生一个空缓存
这是我的变异 Hooks 代码
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
}
}))
}
})
根据我看过的教程,编写optimisticResponse 有效负载和实际的Mutation 响应有效负载应该是相同的,并且不会清空缓存。
是我用错了还是bug?
【问题讨论】:
标签: reactjs graphql apollo react-apollo apollo-client