-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathusePostCodeSnippets.ts
More file actions
79 lines (72 loc) · 2.2 KB
/
usePostCodeSnippets.ts
File metadata and controls
79 lines (72 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import type {
InfiniteData,
UseInfiniteQueryOptions,
UseInfiniteQueryResult,
} from '@tanstack/react-query';
import { useInfiniteQuery } from '@tanstack/react-query';
import { useCallback } from 'react';
import type { PostCodeSnippet } from '../../graphql/posts';
import {
POST_CODE_SNIPPETS_PER_PAGE_DEFAULT,
POST_CODE_SNIPPETS_QUERY,
} from '../../graphql/posts';
import {
generateQueryKey,
getNextPageParam,
RequestKey,
StaleTime,
} from '../../lib/query';
import type { Connection } from '../../graphql/common';
import { gqlClient } from '../../graphql/common';
type UsePostCodeSnippetsData = Connection<PostCodeSnippet>;
export type UsePostCodeSnippetsQueryProps = {
postId: string | undefined;
perPage?: number;
queryOptions?: Omit<
UseInfiniteQueryOptions<UsePostCodeSnippetsData>,
'select' | 'getNextPageParam'
>;
};
export type UsePostCodeSnippetsQuery = UseInfiniteQueryResult<
InfiniteData<UsePostCodeSnippetsData>
>;
export const usePostCodeSnippetsQuery = ({
postId,
perPage = POST_CODE_SNIPPETS_PER_PAGE_DEFAULT,
queryOptions,
}: UsePostCodeSnippetsQueryProps): UsePostCodeSnippetsQuery => {
const enabled = !!postId;
const queryResult = useInfiniteQuery({
queryKey: generateQueryKey(RequestKey.PostCodeSnippets, undefined, {
id: postId,
}),
queryFn: async ({ pageParam }) => {
const result = await gqlClient.request<{
postCodeSnippets: UsePostCodeSnippetsData;
}>(POST_CODE_SNIPPETS_QUERY, {
id: postId,
first: perPage,
after: pageParam,
});
return result.postCodeSnippets;
},
initialPageParam: '',
staleTime: StaleTime.OneHour,
...queryOptions,
enabled:
typeof queryOptions?.enabled !== 'undefined'
? queryOptions.enabled && enabled
: enabled,
getNextPageParam: (lastPage) => getNextPageParam(lastPage?.pageInfo),
select: useCallback((data: InfiniteData<UsePostCodeSnippetsData>) => {
return {
...data,
// filter out last page with no edges returned by api paginator
pages: data.pages.filter(
(pageItem: UsePostCodeSnippetsData) => !!pageItem?.edges.length,
),
};
}, []),
});
return queryResult;
};