import { useEffect, useState } from 'react' import { GetStaticPropsContext, InferGetStaticPropsType } from 'next' import { useRouter } from 'next/router' import Link from 'next/link' import cn from 'classnames' import getSiteInfo from '@lib/bigcommerce/api/operations/get-site-info' import useSearch from '@lib/bigcommerce/products/use-search' import { Layout } from '@components/core' import { Container, Grid } from '@components/ui' import { ProductCard } from '@components/product' export async function getStaticProps({ preview }: GetStaticPropsContext) { const { categories, brands } = await getSiteInfo() return { props: { categories, brands }, } } export default function Home({ categories, brands, }: InferGetStaticPropsType) { const router = useRouter() 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 ) const activeBrand = brands.find( (b) => getSlug(b.node.path) === `brands/${brand}` )?.node const { data } = useSearch({ search: typeof q === 'string' ? q : '', categoryId: activeCategory?.entityId, brandId: activeBrand?.entityId, }) return (
{data ? ( <> {q && (
{data.found ? ( <>Showing {data.products.length} results for ) : ( <>There are no products that match )}{' '} "{q}"
)} ) : (
Searching...
)}
  • Sort
  • Relevance
  • Latest arrivals
  • Trending
  • Price: Low to high
  • Price: High to low
) } Home.Layout = Layout function useSearchMeta(asPath: string) { const [category, setCategory] = useState() const [brand, setBrand] = useState() useEffect(() => { const parts = asPath.split('/') let c = parts[2] let b = parts[3] if (c === 'designers') { c = parts[4] } if (c !== category) setCategory(c) if (b !== brand) setBrand(b) }, [asPath]) 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, '') const getCategoryPath = (slug: string, brand?: string) => `/search${brand ? `/designers/${brand}` : ''}${slug ? `/${slug}` : ''}` const getDesignerPath = (slug: string, category?: string) => { const designer = slug.replace(/^brands/, 'designers') return `/search${designer ? `/${designer}` : ''}${ category ? `/${category}` : '' }` }