import { useState } from 'react'; import { useQuery } from '@apollo/client'; import update from 'immutability-helper'; import get from 'lodash/get'; export const usePagerQuery = ( query, { variables, updateQuery, itemsPath, countPath, skip } ) => { const [loadingMore, setLoadingMore] = useState(false); const { data, loading, fetchMore } = useQuery(query, { variables, skip }); const items = get(data, itemsPath, []); const total = get(data, countPath, 0); const count = items.length; const hasNextPage = count !== total; const loadMore = async () => { setLoadingMore(true); const result = await fetchMore({ query, variables: { ...variables, skip: count }, updateQuery: (previousResult, { fetchMoreResult }) => { if (!fetchMoreResult) { return previousResult; } return update(previousResult, updateQuery(fetchMoreResult)); } }); setLoadingMore(false); return result; }; return { data, items, total, count, loading, loadMore, hasNextPage, loadingMore }; };