useUrlParams.tsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import {useCallback} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import {useLocation} from 'sentry/utils/useLocation';
  4. function useUrlParams(
  5. defaultKey: string,
  6. defaultValue: string
  7. ): {
  8. getParamValue: () => string;
  9. setParamValue: (value: string) => void;
  10. };
  11. function useUrlParams(defaultKey: string): {
  12. getParamValue: () => string;
  13. setParamValue: (value: string) => void;
  14. };
  15. function useUrlParams(): {
  16. getParamValue: (key: string) => string;
  17. setParamValue: (key: string, value: string) => void;
  18. };
  19. function useUrlParams(defaultKey?: string, defaultValue?: string) {
  20. const location = useLocation();
  21. const getParamValue = useCallback(
  22. (key: string) => {
  23. return location.query[key] || defaultValue;
  24. },
  25. [location, defaultValue]
  26. );
  27. const setParamValue = useCallback(
  28. (key: string, value: string) => {
  29. browserHistory.push({
  30. ...location,
  31. query: {
  32. ...location.query,
  33. [key]: value,
  34. },
  35. });
  36. },
  37. [location]
  38. );
  39. const getWithDefault = useCallback(
  40. () => getParamValue(defaultKey || ''),
  41. [getParamValue, defaultKey]
  42. );
  43. const setWithDefault = useCallback(
  44. (value: string) => setParamValue(defaultKey || '', value),
  45. [setParamValue, defaultKey]
  46. );
  47. if (defaultKey !== undefined) {
  48. return {
  49. getParamValue: getWithDefault,
  50. setParamValue: setWithDefault,
  51. };
  52. }
  53. return {
  54. getParamValue,
  55. setParamValue,
  56. };
  57. }
  58. export default useUrlParams;