【问题标题】:GraphQL with Apollo - how to use fetchMoreGraphQL with Apollo - 如何使用 fetchMore
【发布时间】:2017-11-30 04:18:41
【问题描述】:

我对 Apollo fetchMore 方法的理解有问题。我是这个工具的新手,example in doc 对我来说太复杂了。我在互联网上搜索,但找不到更多(当前)示例。你能帮我写一个无限加载数据的最简单的例子吗?我有这个代码:

const productInfo = gql`
  query {
    allProducts { 
      id
      name
      price
      category {
        name
      }
    }
  }`

const ProductsListData = graphql(productInfo)(ProductsList)

我想在每次点击“加载更多”按钮后获取 5 个产品和 5 个更多产品。我理解这个的想法 - cursor e.t.c 但我不知道如何实现它。 (我正在使用 React)

【问题讨论】:

    标签: reactjs pagination graphql apollo apollo-client


    【解决方案1】:

    通过 graphql.college https://www.graphql.college/building-a-github-client-with-react-apollo/查看本教程

    另外,你可以看看我的实现on Github。具体来说,检查query-mutation-with-hoc 分支上的./src/views/profile

    【讨论】:

      【解决方案2】:

      对于无限加载,您可以使用光标。参考 Apollo 文档中的示例,http://dev.apollodata.com/react/pagination.html#cursor-pages

      根据您提供的架构定制它,它看起来像这样(未经测试)

      const ProductsListData = graphql(productInfo, {
        props({ data: { loading, cursor, allProducts, fetchMore } }) {
          return {
            loading,
            allProducts,
            loadMoreEntries: () => {
              return fetchMore({
                variables: {
                  cursor: cursor,
                },
                updateQuery: (previousResult, { fetchMoreResult }) => {
                  const previousEntry = previousResult.entry;
                  const newProducts = fetchMoreResult.allProducts;
                  return {
                    cursor: fetchMoreResult.cursor,
                    entry: {
                      allProducts: [...previousEntry.entry.allProducts, ...newProducts],
                    },
                  };
                },
              });
            },
          };
        },
      })(ProductsList);

      您可能不得不考虑对象的路径,因为这应该与您的架构相似。但在大多数情况下,这就是您的无限滚动分页实现的样子。

      【讨论】:

        猜你喜欢
        • 2019-12-05
        • 2022-08-17
        • 2020-09-13
        • 2021-01-06
        • 2022-07-21
        • 2018-08-24
        • 2020-03-27
        • 2020-03-21
        • 2020-09-07
        相关资源
        最近更新 更多