| 2 | import { useSearchParams } from "react-router-dom"; |
| 3 | |
| 4 | export function useQueryState(key, defaultValue = undefined) { |
| 5 | const [searchParams, setSearchParams] = useSearchParams(); |
| 6 | const [value, setValue] = useState(() => { |
| 7 | const paramValue = searchParams.get(key); |
| 8 | // If there's a value in the URL, use it; otherwise, use defaultValue if provided. |
| 9 | return paramValue !== null ? paramValue : defaultValue; |
| 10 | }); |
| 11 | |
| 12 | // Set the default value in the URL if it's provided and doesn't exist. |
| 13 | useEffect(() => { |
| 14 | if (defaultValue !== undefined && !searchParams.has(key)) { |
| 15 | const newSearchParams = new URLSearchParams(searchParams); |
| 16 | newSearchParams.set(key, defaultValue); |
| 17 | setSearchParams(newSearchParams, { replace: true }); |
| 18 | } |
| 19 | }, [key, defaultValue, searchParams, setSearchParams]); |
| 20 | |
| 21 | // Update the state when the URL changes. |
| 22 | useEffect(() => { |
| 23 | const paramValue = searchParams.get(key); |
| 24 | if (paramValue !== value) { |
| 25 | // Only set the value if it's not null, which indicates that it's present in the URL. |
| 26 | setValue(paramValue !== null ? paramValue : defaultValue); |
| 27 | } |
| 28 | }, [key, defaultValue, value, searchParams]); |
| 29 | |
| 30 | // Function to update both the state and the URL search params. |
| 31 | const setQueryState = useCallback( |
| 32 | (newValue) => { |
| 33 | setValue(newValue); |
| 34 | const newSearchParams = new URLSearchParams(searchParams); |
| 35 | // If newValue is undefined, delete the search param; otherwise, set the new value. |
| 36 | if (newValue === undefined) { |
| 37 | newSearchParams.delete(key); |
| 38 | } else { |
| 39 | newSearchParams.set(key, newValue); |
| 40 | } |
| 41 | setSearchParams(newSearchParams, { replace: true }); |
| 42 | }, |
| 43 | [key, searchParams, setSearchParams] |
| 44 | ); |
| 45 | |
| 46 | return [value, setQueryState]; |
| 47 | } |