Debounce search query url changes
This commit is contained in:
parent
bf2f289e29
commit
aec690a106
|
@ -1,4 +1,6 @@
|
|||
import _ from 'lodash'
|
||||
import { useRouter } from 'next/router'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
|
||||
export type Sort =
|
||||
| 'creator'
|
||||
|
@ -24,19 +26,34 @@ export function useQueryAndSortParams(options?: { defaultSort: Sort }) {
|
|||
router.push(router, undefined, { shallow: true })
|
||||
}
|
||||
|
||||
const setQuery = (query: string | undefined) => {
|
||||
if (query) {
|
||||
router.query.q = query
|
||||
} else {
|
||||
delete router.query.q
|
||||
}
|
||||
const [queryState, setQueryState] = useState(query)
|
||||
|
||||
router.push(router, undefined, { shallow: true })
|
||||
useEffect(() => {
|
||||
setQueryState(query)
|
||||
}, [query])
|
||||
|
||||
// Debounce router query update.
|
||||
const pushQuery = useMemo(
|
||||
() =>
|
||||
_.debounce((query: string | undefined) => {
|
||||
if (query) {
|
||||
router.query.q = query
|
||||
} else {
|
||||
delete router.query.q
|
||||
}
|
||||
router.push(router, undefined, { shallow: true })
|
||||
}, 500),
|
||||
[router]
|
||||
)
|
||||
|
||||
const setQuery = (query: string | undefined) => {
|
||||
setQueryState(query)
|
||||
pushQuery(query)
|
||||
}
|
||||
|
||||
return {
|
||||
sort: sort ?? options?.defaultSort ?? '24-hour-vol',
|
||||
query: query ?? '',
|
||||
query: queryState ?? '',
|
||||
setSort,
|
||||
setQuery,
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user