2024-04-01 09:25:21 +02:00
|
|
|
import { useCallback, useMemo, useRef } from 'preact/hooks'
|
|
|
|
|
import { useHashLocation } from './useHashLocation'
|
|
|
|
|
|
|
|
|
|
export const useQueryString = () => {
|
|
|
|
|
const [location, setLocation] = useHashLocation()
|
|
|
|
|
|
|
|
|
|
const values = useMemo(() => {
|
|
|
|
|
const queryIndex = location.indexOf('?')
|
|
|
|
|
|
|
|
|
|
if (queryIndex === -1) {
|
|
|
|
|
return [location, new URLSearchParams()] as const
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const search = location.slice(queryIndex + 1)
|
|
|
|
|
|
|
|
|
|
return [location.slice(0, queryIndex), new URLSearchParams(search)] as const
|
|
|
|
|
}, [location])
|
|
|
|
|
|
|
|
|
|
const valuesRef = useRef(values)
|
|
|
|
|
valuesRef.current = values
|
|
|
|
|
|
|
|
|
|
const getValues = useCallback(() => {
|
|
|
|
|
const [, searchParams] = valuesRef.current
|
2024-04-01 10:33:20 +02:00
|
|
|
const result = {} as Record<string, string>
|
2024-04-01 09:25:21 +02:00
|
|
|
|
2024-04-01 10:33:20 +02:00
|
|
|
searchParams.forEach((value, key) => {
|
|
|
|
|
result[key] = value
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return result
|
2024-04-01 09:25:21 +02:00
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
const setValues = useCallback((values: Record<string, string>) => {
|
|
|
|
|
const [baseLocation] = valuesRef.current
|
|
|
|
|
|
|
|
|
|
const newParams = new URLSearchParams(values)
|
|
|
|
|
setLocation(`${baseLocation}?${newParams}`)
|
|
|
|
|
}, [])
|
|
|
|
|
|
|
|
|
|
const hookData = useMemo(
|
|
|
|
|
() => ({ getValues, setValues }),
|
|
|
|
|
[getValues, setValues]
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return hookData
|
|
|
|
|
}
|