( pages?: number, )
| 24 | * @returns The query behavior to set on an infinite query. |
| 25 | */ |
| 26 | export function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>( |
| 27 | pages?: number, |
| 28 | ): QueryBehavior<TQueryFnData, TError, InfiniteData<TData, TPageParam>> { |
| 29 | return { |
| 30 | onFetch: (context, query) => { |
| 31 | const options = context.options as InfiniteQueryPageParamsOptions<TData> |
| 32 | const direction = context.fetchOptions?.meta?.fetchMore?.direction |
| 33 | const oldPages = context.state.data?.pages || [] |
| 34 | const oldPageParams = context.state.data?.pageParams || [] |
| 35 | let result: InfiniteData<unknown> = { pages: [], pageParams: [] } |
| 36 | let currentPage = 0 |
| 37 | |
| 38 | const fetchFn = async () => { |
| 39 | let cancelled = false |
| 40 | const signalContext: FetchSignalContext = context |
| 41 | const addSignalProperty = (object: object) => { |
| 42 | addConsumeAwareSignal( |
| 43 | object, |
| 44 | () => context.signal, |
| 45 | () => (cancelled = true), |
| 46 | signalContext[fetchSignal], |
| 47 | ) |
| 48 | } |
| 49 | |
| 50 | const queryFn = ensureQueryFn(context.options, context.fetchOptions) |
| 51 | |
| 52 | // Create function to fetch a page |
| 53 | const fetchPage = async ( |
| 54 | data: InfiniteData<unknown>, |
| 55 | param: unknown, |
| 56 | previous?: boolean, |
| 57 | ): Promise<InfiniteData<unknown>> => { |
| 58 | if (cancelled) { |
| 59 | return Promise.reject(context.signal.reason) |
| 60 | } |
| 61 | |
| 62 | if (param == null && data.pages.length) { |
| 63 | return Promise.resolve(data) |
| 64 | } |
| 65 | |
| 66 | const createQueryFnContext = () => { |
| 67 | const queryFnContext: OmitKeyof< |
| 68 | QueryFunctionContext<QueryKey, unknown>, |
| 69 | 'signal' |
| 70 | > = { |
| 71 | client: context.client, |
| 72 | queryKey: context.queryKey, |
| 73 | pageParam: param, |
| 74 | direction: previous ? 'backward' : 'forward', |
| 75 | meta: context.options.meta, |
| 76 | } |
| 77 | addSignalProperty(queryFnContext) |
| 78 | return queryFnContext as QueryFunctionContext<QueryKey, unknown> |
| 79 | } |
| 80 | |
| 81 | const queryFnContext = createQueryFnContext() |
| 82 | |
| 83 | const page = await queryFn(queryFnContext) |
no outgoing calls
no test coverage detected