Apollo 的 proxy.writeQueries 清空缓存(是否有错误?)

Apollo's proxy.writeQueries emptied cache (bug or not?)

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

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

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

这是我的 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 payload 和实际的 Mutation 响应 payload 应该是一样的,不会清空缓存。

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

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