diff options
Diffstat (limited to 'src/components/useHashParam.js')
| -rw-r--r-- | src/components/useHashParam.js | 48 |
1 files changed, 0 insertions, 48 deletions
diff --git a/src/components/useHashParam.js b/src/components/useHashParam.js deleted file mode 100644 index e43e1e4..0000000 --- a/src/components/useHashParam.js +++ /dev/null | |||
| @@ -1,48 +0,0 @@ | |||
| 1 | import { useState, useEffect, useCallback } from 'react'; | ||
| 2 | |||
| 3 | const getHashSearchParams = (location) => { | ||
| 4 | const hash = location.hash.slice(1); | ||
| 5 | const [prefix, query] = hash.split('?'); | ||
| 6 | |||
| 7 | return [prefix, new URLSearchParams(query)]; | ||
| 8 | }; | ||
| 9 | |||
| 10 | const getHashParam = (key, location = window.location) => { | ||
| 11 | const [_, searchParams] = getHashSearchParams(location); | ||
| 12 | return searchParams.get(key); | ||
| 13 | }; | ||
| 14 | |||
| 15 | const setHashParam = (key, value, location = window.location) => { | ||
| 16 | const [prefix, searchParams] = getHashSearchParams(location); | ||
| 17 | |||
| 18 | if (typeof value === 'undefined') { | ||
| 19 | searchParams.delete(key); | ||
| 20 | } else { | ||
| 21 | searchParams.set(key, value); | ||
| 22 | } | ||
| 23 | |||
| 24 | const search = searchParams.toString(); | ||
| 25 | location.hash = search ? `${prefix}?${search}` : prefix; | ||
| 26 | }; | ||
| 27 | |||
| 28 | const useHashParam = (key) => { | ||
| 29 | const [innerValue, setInnerValue] = useState(); | ||
| 30 | |||
| 31 | useEffect(() => { | ||
| 32 | const handleHashChange = () => setInnerValue(getHashParam(key)); | ||
| 33 | handleHashChange(); | ||
| 34 | window.addEventListener('hashchange', handleHashChange); | ||
| 35 | return () => window.removeEventListener('hashchange', handleHashChange); | ||
| 36 | }, [key]); | ||
| 37 | |||
| 38 | const setValue = useCallback( | ||
| 39 | (value) => { | ||
| 40 | setHashParam(key, value); | ||
| 41 | }, | ||
| 42 | [key] | ||
| 43 | ); | ||
| 44 | |||
| 45 | return [innerValue, setValue]; | ||
| 46 | }; | ||
| 47 | |||
| 48 | export default useHashParam; | ||
