useSearchQueryParam.tsx 858 B

1234567891011121314151617181920212223242526272829
  1. import {useMemo} from 'react';
  2. import debounce from 'lodash/debounce';
  3. import {DEFAULT_DEBOUNCE_DURATION} from 'sentry/constants';
  4. import {decodeScalar} from 'sentry/utils/queryString';
  5. import {useLocation} from 'sentry/utils/useLocation';
  6. import {useNavigate} from 'sentry/utils/useNavigate';
  7. export function useSearchQueryParam(key: string) {
  8. const location = useLocation();
  9. const navigate = useNavigate();
  10. const query = decodeScalar(location.query[key], '').trim();
  11. const setQuery = useMemo(
  12. () =>
  13. debounce(
  14. (searchQuery: string) =>
  15. navigate({
  16. pathname: location.pathname,
  17. query: {...location.query, [key]: searchQuery || undefined},
  18. }),
  19. DEFAULT_DEBOUNCE_DURATION
  20. ),
  21. [location.pathname, location.query, navigate, key]
  22. );
  23. return [query, setQuery] as const;
  24. }