【问题标题】:How to convert apollo client fetchMore updateQuery to apollo cache merge function?如何将 apollo 客户端 fetchMore updateQuery 转换为 apollo 缓存合并功能?
【发布时间】:2020-12-10 20:46:42
【问题描述】:

我正在学习 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 的缓存中用作合并功能。我尝试在许多不同的地方添加合并,但它似乎总是破坏应用程序。

如能提供任何帮助,我们将不胜感激。

【问题讨论】:

    标签: graphql apollo react-apollo apollo-client


    【解决方案1】:

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

    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/

    【讨论】:

    • 你从哪里得到字段的值:'feed'?
    • @Steve 字段是一个映射,它指定要为每个修改的字段调用的修饰符函数。所以这里的“feed”是graphql查询返回的查询字段,即... query Feed($offset: Int, $limit: Int) { feed(offset: $offset, limit: $limit) { ...
    猜你喜欢
    • 2017-03-18
    • 2020-02-03
    • 2021-04-21
    • 2020-11-03
    • 2021-04-17
    • 2021-03-11
    • 2019-03-24
    • 2017-03-08
    相关资源
    最近更新 更多