3512 |
stevensc |
1 |
import { useState, useEffect, useCallback } from 'react';
|
|
|
2 |
|
|
|
3 |
export function useDebouncedSearchParam(paramName, debounceDelay = 500) {
|
|
|
4 |
const getQueryFromUrl = useCallback(() => {
|
|
|
5 |
const params = new URLSearchParams(window.location.search);
|
|
|
6 |
return params.get(paramName);
|
|
|
7 |
}, [paramName]);
|
|
|
8 |
|
|
|
9 |
const [inputValue, setInputValue] = useState(() => getQueryFromUrl() || '');
|
|
|
10 |
const [debouncedValue, setDebouncedValue] = useState(() => getQueryFromUrl() || '');
|
|
|
11 |
|
|
|
12 |
// Effect to initialize inputValue from URL if it changes externally
|
|
|
13 |
// or on initial load if not already set by useState initializer
|
|
|
14 |
useEffect(() => {
|
|
|
15 |
const queryFromUrl = getQueryFromUrl();
|
|
|
16 |
if (queryFromUrl !== null && queryFromUrl !== inputValue) {
|
|
|
17 |
setInputValue(queryFromUrl);
|
|
|
18 |
}
|
|
|
19 |
}, [getQueryFromUrl, inputValue]);
|
|
|
20 |
|
|
|
21 |
// Effect for debouncing inputValue to debouncedValue
|
|
|
22 |
useEffect(() => {
|
|
|
23 |
const handler = setTimeout(() => {
|
|
|
24 |
setDebouncedValue(inputValue);
|
|
|
25 |
}, debounceDelay);
|
|
|
26 |
|
|
|
27 |
return () => {
|
|
|
28 |
clearTimeout(handler);
|
|
|
29 |
};
|
|
|
30 |
}, [inputValue, debounceDelay]);
|
|
|
31 |
|
|
|
32 |
// Effect for updating URL when debouncedValue changes
|
|
|
33 |
useEffect(() => {
|
|
|
34 |
const params = new URLSearchParams(window.location.search);
|
|
|
35 |
const currentParamValue = params.get(paramName);
|
|
|
36 |
|
|
|
37 |
if (debouncedValue) {
|
|
|
38 |
if (currentParamValue !== debouncedValue) {
|
|
|
39 |
params.set(paramName, debouncedValue);
|
|
|
40 |
window.history.replaceState({}, '', `${window.location.pathname}?${params.toString()}`);
|
|
|
41 |
}
|
|
|
42 |
} else {
|
|
|
43 |
if (currentParamValue !== null) {
|
|
|
44 |
params.delete(paramName);
|
|
|
45 |
const newSearch = params.toString();
|
|
|
46 |
window.history.replaceState(
|
|
|
47 |
{},
|
|
|
48 |
'',
|
|
|
49 |
`${window.location.pathname}${newSearch ? '?' : ''}${newSearch}`
|
|
|
50 |
);
|
|
|
51 |
}
|
|
|
52 |
}
|
|
|
53 |
}, [debouncedValue, paramName]);
|
|
|
54 |
|
|
|
55 |
return { inputValue, setInputValue, debouncedValue };
|
|
|
56 |
}
|