はじめに
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/utilities
のconcatPagination
をtypePolicies
内で使うことで 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ベース向けに、offsetLimitPagination
や relayStylePagination
といったutil機能も@apollo/client/utilities
に用意されています。
まとめ
今回はApollo Client3で追加されたページネーション機能をご紹介しました。