useUrlParams.tsx 1.5 KB

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