-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseSearchParam.ts
33 lines (24 loc) · 953 Bytes
/
useSearchParam.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { useEffect, useState } from 'react';
import { isBrowser, off, on } from './misc/util';
const getValue = (search: string, param: string) => new URLSearchParams(search).get(param);
export type UseQueryParam = (param: string) => string | null;
const useSearchParam: UseQueryParam = (param) => {
const location = window.location;
const [value, setValue] = useState<string | null>(() => getValue(location.search, param));
useEffect(() => {
const onChange = () => {
setValue(getValue(location.search, param));
};
on(window, 'popstate', onChange);
on(window, 'pushstate', onChange);
on(window, 'replacestate', onChange);
return () => {
off(window, 'popstate', onChange);
off(window, 'pushstate', onChange);
off(window, 'replacestate', onChange);
};
}, []);
return value;
};
const useSearchParamServer = () => null;
export default isBrowser ? useSearchParam : useSearchParamServer;