Alan Wołejko
Alan Wołejko

Reputation: 452

GraphQL with Apollo - how to use fetchMore

I have a problem with understanding Apollo fetchMore method. I'm new to this tool and example in doc is too much complicated for me. I was searching on the internet but I can't find more (current) examples. Can you help me write a most simple example of infinite loading data? I have this code:

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

const ProductsListData = graphql(productInfo)(ProductsList)

and I want to fetch 5 products and 5 more after every click on 'Load More' button. I understand the idea of this - cursor e.t.c but I don't know how to implement this. (I'm using React)

Upvotes: 5

Views: 18518

Answers (2)

Suleiman AbdulMajeed
Suleiman AbdulMajeed

Reputation: 1141

Check out this tutorial by graphql.college https://www.graphql.college/building-a-github-client-with-react-apollo/

Also, you can take a look at my implementation on Github. Specifically, check ./src/views/profile on the query-mutation-with-hoc branch

Upvotes: -3

Scot Matson
Scot Matson

Reputation: 745

For infinite loading, you would use a cursor. Referencing the example on the Apollo documentation, http://dev.apollodata.com/react/pagination.html#cursor-pages

Tailoring this to your schema you've provided, it would look something like this (Untested)

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);

You'll likely have to play around with the pathing of the objects as this should look similar to your schema. But for the most part this is what your infinite scrolling pagination implementation should look like.

Upvotes: 7

Related Questions