-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
83a64c6
commit 42e2742
Showing
2 changed files
with
57 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import _ from 'lodash'; | ||
import { useState, useCallback, useMemo } from 'react'; | ||
import { useLocation } from 'react-router-dom'; | ||
|
||
const useQueryParamState = (name, defaultValue) => { | ||
const [param, setParam] = useState(); | ||
const location = useLocation(); | ||
|
||
const setQueryStringParameter = useCallback( | ||
value => { | ||
const [base, hashFragment] = window.location.hash.split('?'); | ||
let params = new URLSearchParams(hashFragment); | ||
|
||
if (_.isNil(value) || value === '') { | ||
params.delete(name); | ||
} else { | ||
params.set(name, value); | ||
} | ||
|
||
const newHash = params.toString() ? `${base}?${params}` : base; | ||
|
||
window.location.hash = decodeURIComponent(newHash); | ||
setParam(value); | ||
}, | ||
[name], | ||
); | ||
|
||
const value = useMemo(() => { | ||
const [, hashFragment] = window.location.hash.split('?'); | ||
const params = new URLSearchParams(hashFragment); | ||
return params.get(name) || defaultValue || ''; | ||
}, [location, param, name]); | ||
|
||
return [value, setQueryStringParameter]; | ||
}; | ||
|
||
export { useQueryParamState }; |