Created
September 16, 2019 21:18
-
-
Save andycarrell/be0635a967b368813a00a33a1e67dfab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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