1 import { FetchError } from "@medusajs/js-sdk"
2 import { PaginatedResponse } from "@medusajs/types"
3 import {
4 QueryKey,
5 UseInfiniteQueryOptions,
6 InfiniteData,
7 useInfiniteQuery,
8 } from "@tanstack/react-query"
9
10 /**
11 * Generic hook for infinite queries with pagination support.
12 *
13 * @template TResponse - The response type that must include count, offset, and limit
14 * @template TParams - The query parameters type (offset and limit will be handled internally)
15 * @template TError - The error type (defaults to FetchError)
16 * @template TQueryKey - The query key type (defaults to QueryKey)
17 *
18 * @param config - Configuration object
19 * @param config.queryKey - Function or array that generates the query key
20 * @param config.queryFn - Function that fetches data with offset and limit
21 * @param config.query - Query parameters (offset is ignored, limit is optional)
22 * @param config.options - Additional options for useInfiniteQuery
23 *
24 * @example
25 * ```ts
26 * const { data, fetchNextPage, hasNextPage } = useInfiniteList({
27 * queryKey: (params) => productVariantQueryKeys.list(params),
28 * queryFn: async (params) => sdk.admin.productVariant.list(params),
29 * query: { status: "published" },
30 * })
31 * ```
32 */
33 export const useInfiniteList = <
34 TResponse extends PaginatedResponse<unknown>,
35 TParams extends { offset?: number; limit?: number } = {
36 offset?: number
37 limit?: number
38 },
39 TError = FetchError,
40 TQueryKey extends QueryKey = QueryKey
41 >({
42 queryKey,
43 queryFn,
44 query,
45 options,
46 }: {
47 queryKey: ((params: Omit<TParams, "limit">) => TQueryKey) | TQueryKey
48 queryFn: (params: TParams) => Promise<TResponse>
49 query?: TParams
50 options?: Omit<
51 UseInfiniteQueryOptions<
52 TResponse,
53 TError,
54 InfiniteData<TResponse, number>,
55 TResponse,
56 TQueryKey,
57 number
58 >,
59 "queryKey" | "queryFn" | "initialPageParam" | "getNextPageParam"
60 >
61 }) => {
62 const { limit = 50, offset: _, ..._query } = query ?? {}
63 const resolvedQueryKey =
64 typeof queryKey === "function"
65 ? queryKey(_query as Omit<TParams, "limit">)
66 : queryKey
67 const infiniteQueryKey =
68 resolvedQueryKey[resolvedQueryKey.length - 1] === "__infinite"
69 ? resolvedQueryKey
70 : ([...resolvedQueryKey, "__infinite"] as unknown as TQueryKey)
71
72 return useInfiniteQuery<
73 TResponse,
74 TError,
75 InfiniteData<TResponse, number>,
76 TQueryKey,
77 number
78 >({
79 // Infinite queries must not share the exact same queryKey as non-infinite queries,
80 // since the cached data shape differs (InfiniteData<T> vs T).
81 queryKey: infiniteQueryKey,
82 queryFn: ({ pageParam = 0 }) => {
83 return queryFn({ ..._query, limit, offset: pageParam } as TParams)
84 },
85 initialPageParam: 0,
86 getNextPageParam: (lastPage) => {
87 const moreItemsExist = lastPage.count > lastPage.offset + lastPage.limit
88 return moreItemsExist ? lastPage.offset + lastPage.limit : undefined
89 },
90 ...options,
91 })
92 }