如何使用大量活动查询更新Apollo缓存

时间:2019-06-28 06:24:06

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

我的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缓存,例如:

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

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

...

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

但是,如果我想很好地更新所有缓存的查询...我该如何完成?我是否必须在每个查询的更新功能内 cache.readQuery cache.writeQuery ?那对我来说太疯狂了。

我迷路了。预先感谢。

1 个答案:

答案 0 :(得分:0)

这是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,
      }
    }
  }
})

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

相关问题