(queryStringKey: string)
| 11 | import { useLocation, useNavigate } from "react-router-dom"; |
| 12 | |
| 13 | export const useQueryStringState = (queryStringKey: string) => { |
| 14 | const navigate = useNavigate(); |
| 15 | const location = useLocation(); |
| 16 | const [value, setValue] = React.useState<string | undefined>(); |
| 17 | |
| 18 | const setSelectedValue = React.useCallback( |
| 19 | (val: string | undefined) => { |
| 20 | const searchParams = new URLSearchParams(location.search); |
| 21 | setValue(val); |
| 22 | if (!val) { |
| 23 | searchParams.delete(queryStringKey); |
| 24 | } else { |
| 25 | searchParams.set(queryStringKey, val); |
| 26 | } |
| 27 | navigate( |
| 28 | `${location.pathname}?${searchParams.toString()}${location.hash}`, |
| 29 | { |
| 30 | replace: true, |
| 31 | }, |
| 32 | ); |
| 33 | }, |
| 34 | [ |
| 35 | location.hash, |
| 36 | location.pathname, |
| 37 | location.search, |
| 38 | navigate, |
| 39 | queryStringKey, |
| 40 | ], |
| 41 | ); |
| 42 | |
| 43 | React.useEffect(() => { |
| 44 | const url = new URL(window.location.toString()); |
| 45 | const val = url.searchParams.get(queryStringKey); |
| 46 | if (val) { |
| 47 | setSelectedValue(val); |
| 48 | } |
| 49 | }, [queryStringKey, setSelectedValue]); |
| 50 | |
| 51 | return [value, setSelectedValue] as const; |
| 52 | }; |
no test coverage detected