({
id,
value,
getSelectedOption,
getOptions,
onChange,
enabled,
}: UseFilterMenuOptions)
| 17 | }; |
| 18 | |
| 19 | export const useFilterMenu = ({ |
| 20 | id, |
| 21 | value, |
| 22 | getSelectedOption, |
| 23 | getOptions, |
| 24 | onChange, |
| 25 | enabled, |
| 26 | }: UseFilterMenuOptions) => { |
| 27 | const selectedOptionsCacheRef = useRef<Record<string, SelectFilterOption>>( |
| 28 | {}, |
| 29 | ); |
| 30 | const [query, setQuery] = useState(""); |
| 31 | const debouncedQuery = useDebouncedValue(query, FILTER_DEBOUNCE_MS); |
| 32 | const selectedOptionQuery = useQuery({ |
| 33 | queryKey: [id, "autocomplete", "selected", value], |
| 34 | queryFn: () => { |
| 35 | if (!value) { |
| 36 | return null; |
| 37 | } |
| 38 | |
| 39 | const cachedOption = selectedOptionsCacheRef.current[value]; |
| 40 | if (cachedOption) { |
| 41 | return cachedOption; |
| 42 | } |
| 43 | |
| 44 | return getSelectedOption(); |
| 45 | }, |
| 46 | enabled, |
| 47 | placeholderData: keepPreviousData, |
| 48 | }); |
| 49 | const selectedOption = selectedOptionQuery.data; |
| 50 | const searchOptionsQuery = useQuery({ |
| 51 | queryKey: [id, "autocomplete", "search", debouncedQuery], |
| 52 | queryFn: () => getOptions(debouncedQuery), |
| 53 | enabled, |
| 54 | }); |
| 55 | const searchOptions = useMemo(() => { |
| 56 | if (searchOptionsQuery.isFetching) { |
| 57 | return undefined; |
| 58 | } |
| 59 | |
| 60 | const isDataLoaded = |
| 61 | searchOptionsQuery.isFetched && selectedOptionQuery.isFetched; |
| 62 | |
| 63 | if (!isDataLoaded) { |
| 64 | return undefined; |
| 65 | } |
| 66 | |
| 67 | let options = searchOptionsQuery.data ?? []; |
| 68 | |
| 69 | if (selectedOption) { |
| 70 | options = options.filter( |
| 71 | (option) => option.value !== selectedOption.value, |
| 72 | ); |
| 73 | options = [selectedOption, ...options]; |
| 74 | } |
| 75 | |
| 76 | options = options.filter( |
no test coverage detected