1 import { useSearchParams } from "react-router-dom"
2
3 export const useSelectedParams = ({
4 param,
5 prefix,
6 multiple = false,
7 }: {
8 param: string
9 prefix?: string
10 multiple?: boolean
11 }) => {
12 const [searchParams, setSearchParams] = useSearchParams()
13 const identifier = prefix ? `${prefix}_${param}` : param
14 const offsetKey = prefix ? `${prefix}_offset` : "offset"
15
16 const add = (value: string) => {
17 setSearchParams((prev) => {
18 const newValue = new URLSearchParams(prev)
19
20 const updateMultipleValues = () => {
21 const existingValues = newValue.get(identifier)?.split(",") || []
22
23 if (!existingValues.includes(value)) {
24 existingValues.push(value)
25 newValue.set(identifier, existingValues.join(","))
26 }
27 }
28
29 const updateSingleValue = () => {
30 newValue.set(identifier, value)
31 }
32
33 multiple ? updateMultipleValues() : updateSingleValue()
34 newValue.delete(offsetKey)
35
36 return newValue
37 })
38 }
39
40 const deleteParam = (value?: string) => {
41 const deleteMultipleValues = (prev: URLSearchParams) => {
42 const existingValues = prev.get(identifier)?.split(",") || []
43 const index = existingValues.indexOf(value || "")
44 if (index > -1) {
45 existingValues.splice(index, 1)
46 prev.set(identifier, existingValues.join(","))
47 }
48 }
49
50 const deleteSingleValue = (prev: URLSearchParams) => {
51 prev.delete(identifier)
52 }
53
54 setSearchParams((prev) => {
55 if (value) {
56 multiple ? deleteMultipleValues(prev) : deleteSingleValue(prev)
57 if (!prev.get(identifier)) {
58 prev.delete(identifier)
59 }
60 } else {
61 prev.delete(identifier)
62 }
63 prev.delete(offsetKey)
64 return prev
65 })
66 }
67
68 const get = () => {
69 return searchParams.get(identifier)?.split(",").filter(Boolean) || []
70 }
71
72 return { add, delete: deleteParam, get }
73 }