Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pagination and increment categories to 4 #820

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const LIMIT = 12
// Return current cart info
const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
res,
body: { search, categoryId, brandId, sort },
body: { search, categoryId, brandId, sort, page },
config,
commerce,
}) => {
Expand All @@ -30,6 +30,8 @@ const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
if (brandId && Number.isInteger(Number(brandId)))
url.searchParams.set('brand_id', String(brandId))

if (page) url.searchParams.set('page', String(page))

if (sort) {
const [_sort, direction] = sort.split('-')
const sortValue = SORT[_sort]
Expand All @@ -43,9 +45,12 @@ const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
// We only want the id of each product
url.searchParams.set('include_fields', 'id')

const { data } = await config.storeApiFetch<{ data: { id: number }[] }>(
url.pathname + url.search
)
const { data, meta } = await config.storeApiFetch<{
data: { id: number }[]
meta: any
}>(url.pathname + url.search)

const pagination = meta.pagination

const ids = data.map((p) => String(p.id))
const found = ids.length > 0
Expand Down Expand Up @@ -73,7 +78,7 @@ const getProducts: ProductsEndpoint['handlers']['getProducts'] = async ({
if (product) products.push(product)
})

res.status(200).json({ data: { products, found } })
res.status(200).json({ data: { products, found, pagination } })
}

export default getProducts
9 changes: 8 additions & 1 deletion packages/bigcommerce/src/product/use-search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@ export type SearchProductsInput = {
brandId?: number
sort?: string
locale?: string
page?: string | number
}

export const handler: SWRHook<SearchProductsHook> = {
fetchOptions: {
url: '/api/catalog/products',
method: 'GET',
},
fetcher({ input: { search, categoryId, brandId, sort }, options, fetch }) {
fetcher({
input: { search, categoryId, brandId, sort, page },
options,
fetch,
}) {
// Use a dummy base as we only care about the relative path
const url = new URL(options.url!, 'http://a')

Expand All @@ -27,6 +32,7 @@ export const handler: SWRHook<SearchProductsHook> = {
if (Number.isInteger(brandId))
url.searchParams.set('brandId', String(brandId))
if (sort) url.searchParams.set('sort', sort)
if (page) url.searchParams.set('page', String(page))

return fetch({
url: url.pathname + url.search,
Expand All @@ -42,6 +48,7 @@ export const handler: SWRHook<SearchProductsHook> = {
['categoryId', input.categoryId],
['brandId', input.brandId],
['sort', input.sort],
['page', input.page],
],
swrOptions: {
revalidateOnFocus: false,
Expand Down
2 changes: 2 additions & 0 deletions packages/commerce/src/types/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export type SearchProductsBody = {
brandId?: string | number
sort?: string
locale?: string
page?: string | number
}

export type ProductTypes = {
Expand All @@ -63,6 +64,7 @@ export type SearchProductsHook<T extends ProductTypes = ProductTypes> = {
data: {
products: T['product'][]
found: boolean
pagination: any
}
body: T['searchBody']
input: T['searchBody']
Expand Down
2 changes: 1 addition & 1 deletion site/components/common/Layout/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ const Layout: React.FC<Props> = ({
}) => {
const { acceptedCookies, onAcceptCookies } = useAcceptCookies()
const { locale = 'en-US' } = useRouter()
const navBarlinks = categories.slice(0, 2).map((c) => ({
const navBarlinks = categories.slice(0, 4).map((c) => ({
label: c.name,
href: `/search/${c.slug}`,
}))
Expand Down
47 changes: 44 additions & 3 deletions site/components/search.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import cn from 'clsx'
import type { SearchPropsType } from '@lib/search-props'
import Link from 'next/link'
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/router'

import { Layout } from '@components/common'
Expand All @@ -25,6 +25,7 @@ import {
filterQuery,
getCategoryPath,
getDesignerPath,
getPaginationPath,
useSearchMeta,
} from '@lib/search'

Expand All @@ -34,11 +35,11 @@ export default function Search({ categories, brands }: SearchPropsType) {

const router = useRouter()
const { asPath, locale } = router
const { q, sort } = router.query
const { q, sort, page } = router.query
// `q` can be included but because categories and designers can't be searched
// in the same way of products, it's better to ignore the search input if one
// of those is selected
const query = filterQuery({ sort })
const query = filterQuery({ sort, page })

const { pathname, category, brand } = useSearchMeta(asPath)
const activeCategory = categories.find((cat: any) => cat.slug === category)
Expand All @@ -51,9 +52,14 @@ export default function Search({ categories, brands }: SearchPropsType) {
categoryId: activeCategory?.id,
brandId: (activeBrand as any)?.entityId,
sort: typeof sort === 'string' ? sort : '',
page: typeof page === 'string' ? page : '',
locale,
})

useEffect(() => {
window.scrollTo(0, 0)
}, [page])

const handleClick = (event: any, filter: string) => {
if (filter !== activeFilter) {
setToggleFilter(true)
Expand Down Expand Up @@ -336,6 +342,41 @@ export default function Search({ categories, brands }: SearchPropsType) {
))}
</div>
)}{' '}
<div className="flex justify-center mt-5">
{data?.pagination.total_pages !== data?.pagination.current_page && (
<Link
href={getPaginationPath(
pathname,
data?.pagination.current_page + 1
)}
>
<button
type="button"
className="mr-3 rounded-sm border border-accent-3 px-4 py-3 bg-accent-0 text-sm leading-5 font-medium text-accent-4 hover:text-accent-5 focus:outline-none focus:border-blue-300 focus:shadow-outline-normal active:bg-accent-1 active:text-accent-8 transition ease-in-out duration-150"
>
{' '}
Next{' '}
</button>
</Link>
)}

{data?.pagination.current_page !== 1 && (
<Link
href={getPaginationPath(
pathname,
data?.pagination.current_page - 1
)}
>
<button
type="button"
className="mr-3 rounded-sm border border-accent-3 px-4 py-3 bg-accent-0 text-sm leading-5 font-medium text-accent-4 hover:text-accent-5 focus:outline-none focus:border-blue-300 focus:shadow-outline-normal active:bg-accent-1 active:text-accent-8 transition ease-in-out duration-150"
>
{' '}
Previous{' '}
</button>
</Link>
)}
</div>
</div>

{/* Sort */}
Expand Down
5 changes: 5 additions & 0 deletions site/lib/search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,8 @@ export const getDesignerPath = (path: string, category?: string) => {
category ? `/${category}` : ''
}`
}

export const getPaginationPath = (path: string, currentPage?: number) => {
const category = getSlug(path)
return `${category ? `/${category}` : ''}?page=${currentPage}`
}