5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Apollo Client 3でページネーション

Last updated at Posted at 2020-09-01

はじめに

Apollo Client 3における便利なページネーション機能をご紹介します。

concatPagination

Apollo Clientのページネーションは、これまでoffsetベースの実装だとfetchMoreを使った以下のような実装になっていましたが、

Before

<Feed
  entries={data.entries || []}
  onLoadMore={() =>
    fetchMore({
      variables: {
        offset: data.entries.length
      },
      updateQuery: (prev, { fetchMoreResult }) => {
        if (!fetchMoreResult) return prev;
        return Object.assign({}, prev, {
          entries: [...prev.entries, ...fetchMoreResult.entries]
        });
      }
    })
  }
/>

After

Apollo Client 3から、@apollo/client/utilitiesconcatPaginationtypePolicies内で使うことで updateQuery の記述の必要がなくなりました(fetchMoreにおけるupdateQueryはdeprecated)。


const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        entries: concatPagination(),
      },
    },
  },
});

<Feed
  entries={data.entries || []}
  onLoadMore={() =>
    fetchMore({
      variables: {
        offset: data.entries.length
      }
    })
  }
/>

cursorベース向けに、offsetLimitPaginationrelayStylePagination といったutil機能も@apollo/client/utilitiesに用意されています。

まとめ

今回はApollo Client3で追加されたページネーション機能をご紹介しました。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?