如何将apollo客户端fetchMore updateQuery转换为apollo缓存合并功能?

问题描述

我正在学习apollo和graphQL,并有一个简单的应用程序来显示数据列表,并带有添加到数组的fetchMore函数。

我想删除不赞成使用的updateQuery并使用新的字段策略合并功能。当前的缓存设置和updateQuery如下所示:

const cache = new InMemoryCache({
  typePolicies: {
    client_client: {
      fields: {
        // add local only value to clients
        isEdited: {
          read(value = false) {
            // when writing the new value return new value or false as default
            return value;
          },}
      }
    }
  }
});
  const onFetchMore = () => {
    fetchMore({
      variables: {
        offset: page
      },updateQuery: (previousResult,{ fetchMoreResult,queryVariables }) => {
        return {
          ...previousResult,client_client: [
            ...previousResult.client_client,...fetchMoreResult.client_client,],};
      },});
  }

但是,我似乎无法使它作为apollo客户端v3的缓存中的合并功能工作。我曾尝试在许多不同的地方添加合并,但是合并似乎总是会破坏应用程序。

在此方面的任何帮助将不胜感激。

解决方法

根据文档,在 typePolicies 构造函数中提供的 InMemoryCache 选项中定义字段策略:

const cache = new InMemoryCache({   typePolicies: {
    Query: {
      fields: {
        feed: {
          // Don't cache separate results based on
          // any of this field's arguments.
          keyArgs: false,// Concatenate the incoming list items with
          // the existing list items.
          merge(existing = [],incoming) {
            return [...existing,...incoming];
          },}
      }
    }   } })

然后您只需将 offsetlimit 传递给初始查询:

const { loading,data,fetchMore } = useQuery(GET_ITEMS,{
  variables: {
    offset: 0,limit: 10
  },});

fetchMore 以获得下一次迭代:

fetchMore({
  variables: {
    offset: 10,});

在此处查看文档:{​​{3}}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...