You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 line
1.1KB

  1. import { useEffect, useState } from 'react';
  2. import { useLocation, useNavigate } from 'react-router';
  3. export default function useURLSearchParams() {
  4. const navigate = useNavigate();
  5. const { pathname, search } = useLocation();
  6. const [urlParam, setUrlParam] = useState(new URLSearchParams(search));
  7. const [needApply, setNeedApply] = useState(false);
  8. const setParam = () => {
  9. const path = pathname;
  10. const url = path + '?' + urlParam.toString();
  11. const current = pathname + search;
  12. if (url !== current) {
  13. navigate(url);
  14. }
  15. setNeedApply(false);
  16. };
  17. const appendAll = (list: { key: string; value: string | null | undefined }[]) => {
  18. list.forEach(({ key, value }) => {
  19. urlParam.delete(key);
  20. if (value) {
  21. urlParam.append(key, value);
  22. }
  23. });
  24. urlParam.sort();
  25. setNeedApply(true);
  26. };
  27. useEffect(() => {
  28. setUrlParam(new URLSearchParams(search));
  29. }, [search]);
  30. useEffect(() => {
  31. if (needApply) {
  32. setParam();
  33. }
  34. }, [needApply]);
  35. return {
  36. search,
  37. urlParam,
  38. appendAll,
  39. };
  40. }