Skip to content

Commit fc48cc2

Browse files
add first version useQueryParams hook
1 parent 733973b commit fc48cc2

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ export { default as useOnClickOutside } from './useOnClickOutside';
2323
export { default as useOnlineStatus } from './useOnlineStatus';
2424
export { default as usePrevious } from './usePrevious';
2525
export { default as usePrint } from './usePrint';
26+
export { default as useQueryParams } from './useQueryParams';
2627
export { default as useScript } from './useScript';
2728
export { default as useSpeechRecognition } from './useSpeechRecognition';
2829
export { default as useSpeechSynthesis } from './useSpeechSynthesis';

src/useQueryParams.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { useEffect } from 'react';
2+
import useLocation from './useLocation';
3+
4+
// getParams & setParams
5+
6+
export default function useQueryParams() {
7+
const {
8+
replace, search,
9+
} = useLocation();
10+
11+
const getParams = () => {
12+
const urlSearchParams = new URLSearchParams(search);
13+
const params = Object.fromEntries(urlSearchParams.entries());
14+
return params;
15+
};
16+
17+
const setParams = (params) => {
18+
console.log(params);
19+
const urlSearchParams = new URLSearchParams(params);
20+
replace(`?${urlSearchParams.toString()}`);
21+
22+
console.log(urlSearchParams.toString());
23+
// urlSearchParams.forEach((item) => console.log(item));
24+
// const urlSearchParams = new URLSearchParams();
25+
// Object.entries(params).forEach(([key, value]) => {
26+
// console.log(key, value);
27+
// urlSearchParams.append(key, value);
28+
// });
29+
// replace(`?${urlSearchParams.toString()}`);
30+
};
31+
32+
useEffect(() => {
33+
getParams();
34+
}, [search]);
35+
36+
return {
37+
getParams, setParams,
38+
};
39+
}

0 commit comments

Comments
 (0)