manifold/web/hooks/use-sort-and-query-params.tsx

96 lines
2.3 KiB
TypeScript
Raw Normal View History

2022-08-07 23:50:12 +00:00
import { debounce } from 'lodash'
import { useRouter } from 'next/router'
2022-02-24 04:57:59 +00:00
import { useEffect, useMemo, useState } from 'react'
import { DEFAULT_SORT } from 'web/components/contract-search'
const MARKETS_SORT = 'markets_sort'
export type Sort =
| 'newest'
2022-02-04 22:04:30 +00:00
| 'oldest'
| 'most-traded'
| '24-hour-vol'
2022-05-21 17:44:51 +00:00
| 'close-date'
| 'resolve-date'
| 'last-updated'
| 'score'
export function getSavedSort() {
// TODO: this obviously doesn't work with SSR, common sense would suggest
// that we should save things like this in cookies so the server has them
if (typeof window !== 'undefined') {
return localStorage.getItem(MARKETS_SORT) as Sort | null
} else {
return null
}
}
export function useQueryAndSortParams(options?: {
defaultSort?: Sort
shouldLoadFromStorage?: boolean
}) {
const { defaultSort = DEFAULT_SORT, shouldLoadFromStorage = true } =
options ?? {}
const router = useRouter()
const { s: sort, q: query } = router.query as {
q?: string
s?: Sort
}
const setSort = (sort: Sort | undefined) => {
router.replace({ query: { ...router.query, s: sort } }, undefined, {
shallow: true,
})
if (shouldLoadFromStorage) {
localStorage.setItem(MARKETS_SORT, sort || '')
}
}
const [queryState, setQueryState] = useState(query)
useEffect(() => {
setQueryState(query)
}, [query])
2022-02-24 04:57:59 +00:00
// Debounce router query update.
const pushQuery = useMemo(
() =>
debounce((query: string | undefined) => {
const queryObj = { ...router.query, q: query }
2022-07-30 00:37:34 +00:00
if (!query) delete queryObj.q
router.replace({ query: queryObj }, undefined, {
shallow: true,
})
}, 100),
2022-02-24 04:57:59 +00:00
[router]
)
const setQuery = (query: string | undefined) => {
setQueryState(query)
2022-02-24 04:57:59 +00:00
pushQuery(query)
}
useEffect(() => {
// If there's no sort option, then set the one from localstorage
if (router.isReady && !sort && shouldLoadFromStorage) {
const localSort = localStorage.getItem(MARKETS_SORT) as Sort
if (localSort && localSort !== defaultSort) {
// Use replace to not break navigating back.
router.replace(
{ query: { ...router.query, s: localSort } },
undefined,
{ shallow: true }
)
}
}
})
return {
sort: sort ?? defaultSort,
query: queryState ?? '',
setSort,
setQuery,
}
}