-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(hooks): add options to update search-params
- use push option as default
- Loading branch information
1 parent
ef2ab3c
commit 947c187
Showing
1 changed file
with
17 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,22 @@ | ||
import { useMemo } from 'react'; | ||
import { useLocation } from 'react-router'; | ||
import { useCallback, useMemo } from 'react'; | ||
import { useHistory, useLocation } from 'react-router'; | ||
|
||
export const useSearchParams = () => { | ||
const { search } = useLocation(); | ||
const history = useHistory(); | ||
|
||
return useMemo(() => new URLSearchParams(search), [search]); | ||
const searchParams = useMemo(() => Object.fromEntries(new URLSearchParams(search)), [search]); | ||
const setSearchParams = useCallback( | ||
(newSearchParams: Record<string, string>, method: 'push' | 'replace' = 'push') => { | ||
if (method === 'push') { | ||
history.push({ search: new URLSearchParams(newSearchParams).toString() }); | ||
} | ||
if (method === 'replace') { | ||
history.replace({ search: new URLSearchParams(newSearchParams).toString() }); | ||
} | ||
}, | ||
[history] | ||
); | ||
|
||
return { searchParams, setSearchParams }; | ||
}; |