From 6f763f69131b0eeb085c6fd0862309e161371295 Mon Sep 17 00:00:00 2001 From: Luis Alvarez Date: Tue, 13 Oct 2020 22:20:23 -0500 Subject: [PATCH] Keep the query and sort while navigating --- pages/search.tsx | 47 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/pages/search.tsx b/pages/search.tsx index 40bc3ecf7..7d29968aa 100644 --- a/pages/search.tsx +++ b/pages/search.tsx @@ -22,8 +22,10 @@ export default function Home({ brands, }: InferGetStaticPropsType) { const router = useRouter() - const { q } = router.query - const { category, brand } = useSearchMeta(router.asPath) + const { asPath } = router + const { q, sort } = router.query + const query = filterQuery({ q, sort }) + const { category, brand } = useSearchMeta(asPath) const activeCategory = categories.find( (cat) => getSlug(cat.path) === category ) @@ -42,7 +44,7 @@ export default function Home({
  • - + All Categories
  • @@ -53,7 +55,12 @@ export default function Home({ underline: activeCategory?.entityId === cat.entityId, })} > - + {cat.name} @@ -61,7 +68,7 @@ export default function Home({
  • - + All Designers
  • @@ -72,7 +79,12 @@ export default function Home({ underline: activeBrand?.entityId === node.entityId, })} > - + {node.name} @@ -104,8 +116,16 @@ export default function Home({
    -
  • - Relevance +
  • Sort
  • +
  • + + Relevance +
  • Latest arrivals
  • Trending
  • @@ -127,8 +147,6 @@ function useSearchMeta(asPath: string) { useEffect(() => { const parts = asPath.split('/') - // console.log('parts', parts) - let c = parts[2] let b = parts[3] @@ -143,6 +161,15 @@ function useSearchMeta(asPath: string) { return { category, brand } } +// Removes empty query parameters from the query object +const filterQuery = (query: any) => + Object.keys(query).reduce((obj, key) => { + if (query[key]?.length) { + obj[key] = query[key] + } + return obj + }, {}) + // Remove trailing and leading slash const getSlug = (path: string) => path.replace(/^\/|\/$/g, '')