forked from TanStack/query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusePaginatedQuery.ts
71 lines (62 loc) · 2.05 KB
/
usePaginatedQuery.ts
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
import {
PaginatedQueryConfig,
PaginatedQueryResult,
QueryFunction,
QueryKey,
TypedQueryFunction,
TypedQueryFunctionArgs,
} from '../core/types'
import { getQueryArgs } from '../core/utils'
import { useBaseQuery } from './useBaseQuery'
// A paginated query is more like a "lag" query, which means
// as the query key changes, we keep the results from the
// last query and use them as placeholder data in the next one
// We DON'T use it as initial data though. That's important
// TYPES
export interface UsePaginatedQueryObjectConfig<TResult, TError> {
queryKey: QueryKey
queryFn?: QueryFunction<TResult>
config?: PaginatedQueryConfig<TResult, TError>
}
// HOOK
// Parameter syntax with optional config
export function usePaginatedQuery<TResult = unknown, TError = unknown>(
queryKey: QueryKey,
queryConfig?: PaginatedQueryConfig<TResult, TError>
): PaginatedQueryResult<TResult, TError>
// Parameter syntax with query function and optional config
export function usePaginatedQuery<
TResult,
TError,
TArgs extends TypedQueryFunctionArgs
>(
queryKey: QueryKey,
queryFn: TypedQueryFunction<TResult, TArgs>,
queryConfig?: PaginatedQueryConfig<TResult, TError>
): PaginatedQueryResult<TResult, TError>
export function usePaginatedQuery<TResult = unknown, TError = unknown>(
queryKey: QueryKey,
queryFn: QueryFunction<TResult>,
queryConfig?: PaginatedQueryConfig<TResult, TError>
): PaginatedQueryResult<TResult, TError>
// Object syntax
export function usePaginatedQuery<TResult = unknown, TError = unknown>(
config: UsePaginatedQueryObjectConfig<TResult, TError>
): PaginatedQueryResult<TResult, TError>
// Implementation
export function usePaginatedQuery<TResult, TError>(
arg1: any,
arg2?: any,
arg3?: any
): PaginatedQueryResult<TResult, TError> {
const [queryKey, config] = getQueryArgs<TResult, TError>(arg1, arg2, arg3)
const result = useBaseQuery(queryKey, {
keepPreviousData: true,
...config,
})
return {
...result,
resolvedData: result.data,
latestData: result.isPreviousData ? undefined : result.data,
}
}