Skip to content

Instantly share code, notes, and snippets.

@andycarrell
Created September 16, 2019 21:18
Show Gist options
  • Save andycarrell/be0635a967b368813a00a33a1e67dfab to your computer and use it in GitHub Desktop.
Save andycarrell/be0635a967b368813a00a33a1e67dfab to your computer and use it in GitHub Desktop.
/**
* Following https://graphql.org/learn/pagination/ pagination spec
*/
import { useQuery } from '@apollo/react-hooks'
function usePaginationFor(name, queryResult) {
const { data = {}, fetchMore, variables, ...rest } = queryResult
const { pageInfo = {} } = data[name] || {}
const fetchMoreAndMerge = () =>
fetchMore({
variables: { ...variables, after: pageInfo.endCursor },
updateQuery: (previousResult, { fetchMoreResult }) => {
return {
[name]: {
...previousResult[name],
...fetchMoreResult[name],
edges: [
...previousResult[name].edges,
...fetchMoreResult[name].edges
]
}
}
}
})
return { data, fetchMore: fetchMoreAndMerge, variables, ...rest }
}
// usage
const { fetchMore } = usePaginationFor('searchAccounts', useQuery(/* query */))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment