-
Notifications
You must be signed in to change notification settings - Fork 2
/
use-query-params.ts
53 lines (38 loc) 路 1.37 KB
/
use-query-params.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { useHistory } from './use-history'
export const useQueryParams = () => {
const history = useHistory()
const urlParams = new URLSearchParams(window.location.search)
const get = (param: string) => {
for (const [key, value] of urlParams) {
if (param === key) {
return value
}
}
}
const getAll = () => {
const keys = new Map()
for (const [key, value] of urlParams) {
keys.set(key, value)
}
return keys
}
const set = (key: string, value: string | number) => {
const isFound = getAll().has(key)
if (isFound) {
urlParams.set(key, value as string)
} else {
urlParams.append(key, value as string)
}
const newRelativePathQuery = window.location.pathname + '?' + urlParams.toString()
history.push(newRelativePathQuery)
}
const setEncoded = (obj: { [s: string]: string | number } | ArrayLike<string>) => {
const encodedParams = new URLSearchParams()
for (const [key, value] of Object.entries(obj)) {
encodedParams.append(key, value as string)
}
const newRelativePathQuery = window.location.pathname + '?' + encodedParams.toString()
history.push(newRelativePathQuery)
}
return { urlParams: getAll(), get, set, setEncoded }
}