Store users's last sort in localstorage

This commit is contained in:
Austin Chen 2022-03-13 14:46:09 -07:00
parent e5d02dde06
commit d053fb6cb7
2 changed files with 24 additions and 2 deletions

View File

@ -305,6 +305,7 @@ export function CreatorContractsList(props: { creator: User }) {
const { query, setQuery, sort, setSort } = useQueryAndSortParams({
defaultSort: 'all',
shouldLoadFromStorage: false,
})
useEffect(() => {

View File

@ -2,6 +2,8 @@ import _ from 'lodash'
import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react'
const MARKETS_SORT = 'markets_sort'
export type Sort =
| 'creator'
| 'tag'
@ -14,7 +16,13 @@ export type Sort =
| 'resolved'
| 'all'
export function useQueryAndSortParams(options?: { defaultSort: Sort }) {
export function useQueryAndSortParams(options?: {
defaultSort: Sort
shouldLoadFromStorage?: boolean
}) {
const { defaultSort, shouldLoadFromStorage } = _.defaults(options, {
shouldLoadFromStorage: true,
})
const router = useRouter()
const { s: sort, q: query } = router.query as {
@ -25,6 +33,9 @@ export function useQueryAndSortParams(options?: { defaultSort: Sort }) {
const setSort = (sort: Sort | undefined) => {
router.query.s = sort
router.push(router, undefined, { shallow: true })
if (shouldLoadFromStorage) {
localStorage.setItem(MARKETS_SORT, sort || '')
}
}
const [queryState, setQueryState] = useState(query)
@ -52,8 +63,18 @@ export function useQueryAndSortParams(options?: { defaultSort: Sort }) {
pushQuery(query)
}
useEffect(() => {
// If there's no sort option, then set the one from localstorage
if (!sort && shouldLoadFromStorage) {
const localSort = localStorage.getItem(MARKETS_SORT) as Sort
if (localSort) {
setSort(localSort)
}
}
})
return {
sort: sort ?? options?.defaultSort ?? '24-hour-vol',
sort: sort ?? defaultSort ?? '24-hour-vol',
query: queryState ?? '',
setSort,
setQuery,