Last active
September 29, 2021 14:25
-
-
Save Tsugami/02bfe9615100c1571f96eacb8042c47f to your computer and use it in GitHub Desktop.
custom pagination for apollo cache
This file contains 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
const cache = new InMemoryCache({ | |
typePolicies: { | |
Query: { | |
fields: { | |
ShortMedia: ShortMediaStylePagination(), | |
}, | |
}, | |
}, | |
}); |
This file contains 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
import { FieldPolicy } from '@apollo/client'; | |
type TExistingShortMedia<TNode> = { | |
edges: TNode[]; | |
_search: string; | |
totalCount: number; | |
count: number; | |
totalPages: number; | |
hasNextPage: boolean; | |
}; | |
const emptyData = { | |
// _search is customized to compare when variables change | |
_search: '', | |
edges: [], | |
totalCount: 0, | |
count: 0, | |
totalPages: 0, | |
hasNextPage: false, | |
}; | |
const removeDuplicateID = <A extends { tmdb: unknown }>(arr: A[]) => | |
arr.filter((v, i, a) => a.findIndex((t) => t.tmdb === v.tmdb) === i); | |
export default function ShortMediaStylePagination<TNode extends { tmdb: unknown }>(): FieldPolicy< | |
TExistingShortMedia<TNode> | null, | |
Partial<TExistingShortMedia<TNode>> | null, | |
Partial<TExistingShortMedia<TNode>> | null | |
> { | |
return { | |
keyArgs: false, | |
merge(existing = emptyData, incoming, { args }) { | |
if (!existing._search || existing._search !== args.search) { | |
return { ...emptyData, ...incoming, _search: args.search }; | |
} | |
return { | |
...existing, | |
...incoming, | |
_search: args.search, | |
edges: removeDuplicateID([...existing.edges, ...incoming.edges]), | |
}; | |
}, | |
}; | |
} |
This file contains 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
const GET_SHORT_MEDIA_QUERY = gql` | |
${SHORT_MOVIE_INFO_FIELDS} | |
query GetShortMediaQuery($search: String!, $page: Int!) { | |
ShortMedia(search: $search, page: $page) { | |
totalCount | |
hasNextPage | |
edges { | |
...SHORT_MOVIE_INFO_FIELDS | |
} | |
} | |
} | |
`; | |
// .... | |
const [ | |
loadMedia, | |
{ loading, data, error, fetchMore }, | |
] = useLazyQuery<GetShortMediaQuery, GetShortMediaQueryVariables>(GET_SHORT_MEDIA_QUERY, { | |
fetchPolicy: 'network-only', | |
nextFetchPolicy: 'network-only', | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment