({
fallbackFilter = "",
searchParams,
onSearchParamsChange,
onUpdate,
}: UseFilterConfig)
| 57 | export const useFilterParamsKey = "filter"; |
| 58 | |
| 59 | export const useFilter = ({ |
| 60 | fallbackFilter = "", |
| 61 | searchParams, |
| 62 | onSearchParamsChange, |
| 63 | onUpdate, |
| 64 | }: UseFilterConfig): UseFilterResult => { |
| 65 | const query = searchParams.get(useFilterParamsKey) ?? fallbackFilter; |
| 66 | |
| 67 | const update = (newValues: string | FilterValues) => { |
| 68 | const serialized = |
| 69 | typeof newValues === "string" ? newValues : stringifyFilter(newValues); |
| 70 | const noUpdateNeeded = query === serialized; |
| 71 | if (noUpdateNeeded) { |
| 72 | return; |
| 73 | } |
| 74 | |
| 75 | /** |
| 76 | * @todo 2025-07-15 - We have a slightly nasty bug here, where trying to |
| 77 | * update state via immutable state updates causes our code to break. |
| 78 | * |
| 79 | * In theory, it would be better to make a copy of the search params. We |
| 80 | * can then mutate and dispatch the copy instead of the original. Doing |
| 81 | * that causes other parts of our existing logic to break, though. |
| 82 | * That's a sign that our other code is slightly broken, and only just |
| 83 | * happens to work by chance right now. |
| 84 | */ |
| 85 | searchParams.set(useFilterParamsKey, serialized); |
| 86 | onSearchParamsChange(searchParams); |
| 87 | onUpdate?.(serialized); |
| 88 | }; |
| 89 | |
| 90 | const { debounced: debounceUpdate, cancelDebounce } = useDebouncedFunction( |
| 91 | update, |
| 92 | 500, |
| 93 | ); |
| 94 | |
| 95 | return { |
| 96 | query, |
| 97 | update, |
| 98 | debounceUpdate, |
| 99 | cancelDebounce, |
| 100 | values: parseFilterQuery(query), |
| 101 | used: query !== "" && query !== fallbackFilter, |
| 102 | }; |
| 103 | }; |
| 104 | |
| 105 | const parseFilterQuery = (filterQuery: string): FilterValues => { |
| 106 | if (filterQuery === "") { |
no test coverage detected