【问题标题】:How update Apollo Cache with a lot of active queries如何使用大量活动查询更新 Apollo Cache
【发布时间】:2019-11-10 02:46:05
【问题描述】:

我的 Apollo 缓存中存储了很多活动查询,例如:

items(isPublished: true, orderBy: "name", filterByName: "")
items(isPublished: true, orderBy: "name", filterByName: "home")
items(isPublished: false, orderBy: "name", filterByName: "home")
items(isPublished: true, orderBy: "age", filterByName: "home")
...

因此,对于同一个查询 (GET_ITEMS),可能会有很多可能的变量,过滤器也越来越多。当我想添加、移动或删除一个项目时,我会使用 Mutation 组件的 update 属性来更新 Apollo Cache,例如:

import gql from "graphql-tag";
import { Mutation } from "react-apollo";

const ADD_ITEM = gql`
  mutation AddItem(...
`;

...

<Mutation mutation={ADD_ITEM} variables={...} update={() => ...} />

但是,如果我想很好地更新我所有的缓存查询……我该如何完成呢?我是否必须在每个查询的更新函数中 cache.readQuerycache.writeQuery ?这对我来说太疯狂了。

我迷路了。提前致谢。

【问题讨论】:

    标签: reactjs graphql apollo react-apollo graphql-tag


    【解决方案1】:

    这是 ApolloClient 的不幸限制之一,但可以通过使用apollo-link-watched-mutation 来解决。该链接允许您通过 操作名称 关联突变和查询,这样对于具有特定操作名称的任何突变,都可以更新具有特定操作名称的所有查询。这种方法最大的缺点是它将更新逻辑移到了组件之外并进入了客户端配置,这可能会造成一些混淆。

    示例用法,给定名为 AddItem 的突变和名为 Items 的查询:

    const cache = new InMemoryCache()
    const link = new WatchedMutationLink(cache, {
      AddItem: {
        Items: ({ mutation, query }) => {
          const addedItem = mutation.result.data.addItem
          const items = query.result.items
          const items.push(addedItem)
          return {
             ...query.result,
            items,
          }
        }
      }
    })
    

    请注意,您可以检查传递给函数的查询和突变,以确定需要更改的内容(如果有的话)。您的实际代码可能会根据您的查询的实际外观而有所不同,这是一个示例。有关更多详细信息,请参阅文档。

    【讨论】:

    • 谢谢丹尼尔。这个包太棒了。但我不知道它是否对未来和下一个 Apollo 版本有足够的支持。我会使用它,但我会等待可能的更改
    猜你喜欢
    • 2022-08-17
    • 2020-05-11
    • 2021-11-26
    • 2022-06-20
    • 2023-03-10
    • 2020-09-29
    • 2020-01-04
    • 2020-06-19
    • 2017-05-29
    相关资源
    最近更新 更多