Skip to content

Instantly share code, notes, and snippets.

@Tsugami
Last active September 29, 2021 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tsugami/02bfe9615100c1571f96eacb8042c47f to your computer and use it in GitHub Desktop.
Save Tsugami/02bfe9615100c1571f96eacb8042c47f to your computer and use it in GitHub Desktop.
custom pagination for apollo cache
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
ShortMedia: ShortMediaStylePagination(),
},
},
},
});
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]),
};
},
};
}
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