summaryrefslogtreecommitdiff
path: root/src/hooks/useQuery.ts
blob: 821dfe4e3465a9b372d471a3a2cf0e533d5fd2fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { useHistory } from 'react-router-dom';

interface UseQuery {
  query: Record<string, string>;
  setQuery: (query: Record<string, string>) => void;
}

const useQuery = (): UseQuery => {
  const history = useHistory();
  const searchParams = new URLSearchParams(history.location.search);
  const query = Object.fromEntries(searchParams);

  const setQuery = (newQuery: Record<string, string>): void => {
    const queryString = new URLSearchParams(newQuery).toString();
    history.push({ search: queryString && `?${queryString}` });
  };

  return { query, setQuery };
};

export default useQuery;