From d053fb6cb74ddf826e6e2bab67857346c6566ee2 Mon Sep 17 00:00:00 2001 From: Austin Chen Date: Sun, 13 Mar 2022 14:46:09 -0700 Subject: [PATCH] Store users's last sort in localstorage --- web/components/contracts-list.tsx | 1 + web/hooks/use-sort-and-query-params.tsx | 25 +++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/web/components/contracts-list.tsx b/web/components/contracts-list.tsx index d64df8d8..214c5e7b 100644 --- a/web/components/contracts-list.tsx +++ b/web/components/contracts-list.tsx @@ -305,6 +305,7 @@ export function CreatorContractsList(props: { creator: User }) { const { query, setQuery, sort, setSort } = useQueryAndSortParams({ defaultSort: 'all', + shouldLoadFromStorage: false, }) useEffect(() => { diff --git a/web/hooks/use-sort-and-query-params.tsx b/web/hooks/use-sort-and-query-params.tsx index 3eca5f3c..3b669718 100644 --- a/web/hooks/use-sort-and-query-params.tsx +++ b/web/hooks/use-sort-and-query-params.tsx @@ -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,