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 id?: string
17 q?: string
18 offset?: number
19 limit?: number
20 }
21
22 export const useComboboxData = <
23 TResponse extends ComboboxExternalData,
24 TParams extends ComboboxQueryParams,
25 TOption extends { label: string; value: string } = {
26 label: string
27 value: string
28 }
29 >({
30 queryKey,
31 queryFn,
32 getOptions,
33 defaultValue,
34 defaultValueKey,
35 selectedValue,
36 pageSize = 10,
37 enabled = true,
38 }: {
39 queryKey: QueryKey
40 queryFn: (params: TParams) => Promise<TResponse>
41 getOptions: (data: TResponse) => TOption[]
42 defaultValueKey?: keyof TParams
43 defaultValue?: string | string[]
44 selectedValue?: string
45 pageSize?: number
46 enabled?: boolean
47 }) => {
48 const { searchValue, onSearchValueChange, query } = useDebouncedSearch()
49
50 const queryInitialDataBy = defaultValueKey || "id"
51 const { data: initialData } = useQuery({
52 queryKey: [...queryKey, defaultValue].filter(Boolean) as QueryKey,
53 queryFn: async () => {
54 return queryFn({
55 [queryInitialDataBy]: defaultValue,
56 limit: Array.isArray(defaultValue) ? defaultValue.length : 1,
57 } as TParams)
58 },
59 enabled: !!defaultValue && enabled,
60 })
61
62 // always load selected value in case current data dosn't contain the value
63 const { data: selectedData } = useQuery({
64 queryKey: [...queryKey, selectedValue].filter(Boolean) as QueryKey,
65 queryFn: async () => {
66 return queryFn({
67 id: selectedValue,
68 limit: 1,
69 } as TParams)
70 },
71 enabled: !!selectedValue && enabled,
72 })
73
74 const { data, ...rest } = useInfiniteQuery({
75 // prevent infinite query response shape beeing stored under regualr list reponse QKs
76 queryKey: [...queryKey, "_cbx_", query].filter(Boolean) as QueryKey,
77 queryFn: async ({ pageParam = 0 }) => {
78 return await queryFn({
79 q: query,
80 limit: pageSize,
81 offset: pageParam,
82 } as TParams)
83 },
84 initialPageParam: 0,
85 getNextPageParam: (lastPage) => {
86 const moreItemsExist = lastPage.count > lastPage.offset + lastPage.limit
87 return moreItemsExist ? lastPage.offset + lastPage.limit : undefined
88 },
89 placeholderData: keepPreviousData,
90 enabled: enabled,
91 })
92
93 const options = data?.pages.flatMap((page) => getOptions(page)) ?? []
94 const defaultOptions = initialData ? getOptions(initialData) : []
95 const selectedOptions = selectedData ? getOptions(selectedData) : []
96 /**
97 * If there are no options and the query is empty, then the combobox should be disabled,
98 * as there is no data to search for.
99 */
100 const disabled =
101 (!rest.isPending && !options.length && !searchValue) || !enabled
102
103 // make sure that the default value is included in the options
104 if (defaultValue && defaultOptions.length && !searchValue) {
105 defaultOptions.forEach((option) => {
106 if (!options.find((o) => o.value === option.value)) {
107 options.unshift(option)
108 }
109 })
110 }
111
112 if (selectedValue && selectedOptions.length) {
113 selectedOptions.forEach((option) => {
114 if (!options.find((o) => o.value === option.value)) {
115 options.unshift(option)
116 }
117 })
118 }
119
120 return {
121 options,
122 searchValue,
123 onSearchValueChange,
124 disabled,
125 ...rest,
126 }
127 }