Skip to content

Commit

Permalink
feat(hooks): add options to update search-params
Browse files Browse the repository at this point in the history
- use push option as default
  • Loading branch information
SimonGolms committed Aug 25, 2022
1 parent ef2ab3c commit 947c187
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/utils/useSearchParams.ts
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 };
};

0 comments on commit 947c187

Please sign in to comment.