|
- import { useEffect, useState } from 'react';
- import { useLocation, useNavigate } from 'react-router';
-
- export default function useURLSearchParams() {
- const navigate = useNavigate();
- const { pathname, search } = useLocation();
-
- const [urlParam, setUrlParam] = useState(new URLSearchParams(search));
- const [needApply, setNeedApply] = useState(false);
-
- const setParam = () => {
- const path = pathname;
- const url = path + '?' + urlParam.toString();
-
- const current = pathname + search;
- if (url !== current) {
- navigate(url);
- }
- setNeedApply(false);
- };
-
- const appendAll = (list: { key: string; value: string | null | undefined }[]) => {
- list.forEach(({ key, value }) => {
- urlParam.delete(key);
- if (value) {
- urlParam.append(key, value);
- }
- });
- urlParam.sort();
- setNeedApply(true);
- };
-
- useEffect(() => {
- setUrlParam(new URLSearchParams(search));
- }, [search]);
-
- useEffect(() => {
- if (needApply) {
- setParam();
- }
- }, [needApply]);
-
- return {
- search,
- urlParam,
- appendAll,
- };
- }
|