forked from canada-ca/tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSearchParam.js
More file actions
56 lines (48 loc) · 1.5 KB
/
useSearchParam.js
File metadata and controls
56 lines (48 loc) · 1.5 KB
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
54
55
56
import React, { useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
function useSearchParam({ name, validOptions, defaultValue }) {
const { search } = useLocation()
const navigate = useNavigate()
const searchParams = React.useMemo(() => {
return new URLSearchParams(search)
}, [search])
const parseVal = (value) => {
try {
return JSON.parse(value)
} catch {
return value
}
}
const value = searchParams.get(name) || defaultValue
const searchValue = !validOptions || validOptions.includes(value) ? parseVal(value) : defaultValue
const setSearchParams = React.useCallback(
(value) => {
if (Array.isArray(value)) {
if (!value) {
searchParams.delete(name)
} else {
searchParams.set(name, JSON.stringify(value))
}
} else {
if (!value || (validOptions && !validOptions.includes(value))) {
searchParams.delete(name)
} else {
searchParams.set(name, value)
}
}
navigate({ search: searchParams.toString(), replace: true })
},
[searchParams, navigate, name, validOptions],
)
useEffect(() => {
if (!validOptions || validOptions.includes(value)) {
if (value === null || value === '') {
setSearchParams(defaultValue)
}
} else {
setSearchParams(defaultValue)
}
}, [value, validOptions, defaultValue, setSearchParams])
return { searchValue, setSearchParams }
}
export default useSearchParam