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

use*_*991 5 apollo graphql react-apollo apollo-client

我正在学习 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;
          },
        }
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
  const onFetchMore = () => {
    fetchMore({
      variables: {
        offset: page
      },
      updateQuery: (previousResult, { fetchMoreResult, queryVariables }) => {
        return {
          ...previousResult,
          client_client: [
            ...previousResult.client_client,
            ...fetchMoreResult.client_client,
          ],
        };
      },
    });
  }
Run Code Online (Sandbox Code Playgroud)

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

任何有关如何做到这一点的帮助将不胜感激。

Waw*_*mau 1

根据文档,在构造函数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];
          },
        }
      }
    }   } })
Run Code Online (Sandbox Code Playgroud)

然后您只需将offset和传递limit给初始查询:

const { loading, data, fetchMore } = useQuery(GET_ITEMS, {
  variables: {
    offset: 0,
    limit: 10
  },
});
Run Code Online (Sandbox Code Playgroud)

fetchMore获得下一次迭代:

fetchMore({
  variables: {
    offset: 10,
    limit: 10
  },
});
Run Code Online (Sandbox Code Playgroud)

在此处查看文档: https: //www.apollographql.com/docs/react/pagination/core-api/