1 import {
2 QueryKey,
3 keepPreviousData,
4 useInfiniteQuery,
5 useQuery,
6 } from "@tanstack/react-query";
7 import { useDebouncedSearch } from "./use-debounced-search";
8
9 type ComboboxExternalData = {
10 offset: number;
11 limit: number;
12 count: number;
13 };
14
15 type ComboboxQueryParams = {
16 q?: string;
17 offset?: number;
18 limit?: number;
19 };
20
21 export const useComboboxData = <
22 TResponse extends ComboboxExternalData,
23 TParams extends ComboboxQueryParams
24 >({
25 queryKey,
26 queryFn,
27 getOptions,
28 defaultValue,
29 defaultValueKey,
30 pageSize = 10,
31 }: {
32 queryKey: QueryKey;
33 queryFn: (params: TParams) => Promise<TResponse>;
34 getOptions: (data: TResponse) => { label: string; value: string }[];
35 defaultValueKey?: keyof TParams;
36 defaultValue?: string | string[];
37 pageSize?: number;
38 }) => {
39 const { searchValue, onSearchValueChange, query } = useDebouncedSearch();
40
41 const queryInitialDataBy = defaultValueKey || "id";
42 const { data: initialData } = useQuery({
43 queryKey: queryKey,
44 queryFn: async () => {
45 return queryFn({
46 [queryInitialDataBy]: defaultValue,
47 limit: Array.isArray(defaultValue) ? defaultValue.length : 1,
48 } as TParams);
49 },
50 enabled: !!defaultValue,
51 });
52
53 const { data, ...rest } = useInfiniteQuery({
54 queryKey: [...queryKey, query],
55 queryFn: async ({ pageParam = 0 }) => {
56 return await queryFn({
57 q: query,
58 limit: pageSize,
59 offset: pageParam,
60 } as TParams);
61 },
62 initialPageParam: 0,
63 getNextPageParam: (lastPage) => {
64 const moreItemsExist = lastPage.count > lastPage.offset + lastPage.limit;
65 return moreItemsExist ? lastPage.offset + lastPage.limit : undefined;
66 },
67 placeholderData: keepPreviousData,
68 });
69
70 const options = data?.pages.flatMap((page) => getOptions(page)) ?? [];
71 const defaultOptions = initialData ? getOptions(initialData) : [];
72
73 /**
74 * If there are no options and the query is empty, then the combobox should be disabled,
75 * as there is no data to search for.
76 */
77 const disabled = !rest.isPending && !options.length && !searchValue;
78
79 // make sure that the default value is included in the options
80 if (defaultValue && defaultOptions.length && !searchValue) {
81 defaultOptions.forEach((option) => {
82 if (!options.find((o) => o.value === option.value)) {
83 options.unshift(option);
84 }
85 });
86 }
87
88 return {
89 options,
90 searchValue,
91 onSearchValueChange,
92 disabled,
93 ...rest,
94 };
95 };