Fix query params

This commit is contained in:
James Grugett 2022-08-07 16:50:12 -07:00
parent a9120312af
commit b6b670214d
2 changed files with 4 additions and 53 deletions

View File

@ -1,4 +1,4 @@
import { defaults, debounce } from 'lodash'
import { debounce } from 'lodash'
import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react'
import { DEFAULT_SORT } from 'web/components/contract-search'
@ -25,53 +25,6 @@ export function getSavedSort() {
}
}
export function useInitialQueryAndSort(options?: {
defaultSort: Sort
shouldLoadFromStorage?: boolean
}) {
const { defaultSort, shouldLoadFromStorage } = defaults(options, {
defaultSort: DEFAULT_SORT,
shouldLoadFromStorage: true,
})
const router = useRouter()
const [initialSort, setInitialSort] = useState<Sort | undefined>(undefined)
const [initialQuery, setInitialQuery] = useState('')
useEffect(() => {
// If there's no sort option, then set the one from localstorage
if (router.isReady) {
const { s: sort, q: query } = router.query as {
q?: string
s?: Sort
}
setInitialQuery(query ?? '')
if (!sort && shouldLoadFromStorage) {
console.log('ready loading from storage ', sort ?? defaultSort)
const localSort = getSavedSort()
if (localSort) {
// Use replace to not break navigating back.
router.replace(
{ query: { ...router.query, s: localSort } },
undefined,
{ shallow: true }
)
}
setInitialSort(localSort ?? defaultSort)
} else {
setInitialSort(sort ?? defaultSort)
}
}
}, [defaultSort, router.isReady, shouldLoadFromStorage])
return {
initialSort,
initialQuery,
}
}
export function useQueryAndSortParams(options?: {
defaultSort?: Sort
shouldLoadFromStorage?: boolean

View File

@ -1,13 +1,12 @@
import { Answer } from 'common/answer'
import { searchInAny } from 'common/util/parse'
import { sortBy } from 'lodash'
import { useState } from 'react'
import { ContractsGrid } from 'web/components/contract/contracts-list'
import { LoadingIndicator } from 'web/components/loading-indicator'
import { useContracts } from 'web/hooks/use-contracts'
import {
Sort,
useInitialQueryAndSort,
useQueryAndSortParams,
} from 'web/hooks/use-sort-and-query-params'
const MAX_CONTRACTS_RENDERED = 100
@ -27,9 +26,8 @@ export default function ContractSearchFirestore(props: {
const contracts = useContracts()
const { querySortOptions, additionalFilter } = props
const { initialSort, initialQuery } = useInitialQueryAndSort(querySortOptions)
const [sort, setSort] = useState(initialSort ?? 'score')
const [query, setQuery] = useState(initialQuery)
const { query, setQuery, sort, setSort } =
useQueryAndSortParams(querySortOptions)
let matches = (contracts ?? []).filter((c) =>
searchInAny(