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

标签 graphql apollo 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;
          },
        }
      }
    }
  }
});
  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,
    limit: 10
  },
});

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

关于graphql - 如何将 apollo 客户端 fetchMore updateQuery 转换为 apollo 缓存合并功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63523293/

相关文章:

javascript - 突变通过 react-adopt 触发两次

graphql - Apollo GraphQL 服务器 : filter (or sort) by a field that is resolved separately

node.js - 如何从 apollo 服务器发送错误消息

python - 如何更改 django-graphql-jwt 中的默认值 'username'

graphql - 不允许在 GraphQL Schema 中使用空字符串

reactjs - 状态变化时如何防止 useQuery 运行?

node.js - 为什么即使已指定值,Apollo 客户端仍将空值插入到所有字段的表中?

node.js - Typescript 找不到 .d.ts 文件

javascript - ApolloClient 不是一个构造函数react-apollo

reactjs - AWS AppSync + React-Apollo Query/useQuery 引发异常 this.currentObservable.query.getCurrentResult 不是函数