【问题标题】:Apollo's proxy.writeQueries emptied cache (bug or not?)Apollo 的 proxy.writeQueries 清空缓存(bug 与否?)
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 2020-11-03
      • 2021-02-22
      • 2014-07-09
      • 2021-04-06
      • 2023-04-06
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多