Retrieve a Category

List products in a category.

On this page

In this guide, you'll learn how to retrieve a category's products in the storefront.

In your storefront, you may want to allow customers to browse products by category. To do so, you can retrieve the products that belong to a category and display them in your storefront.

To retrieve a category's products in the storefront, send a request to the List Products API route passing it the category_id query parameter:

Tip: Learn how to install and configure the JS SDK in the Getting started guide.

React

tsx

tsxCopy
"use client" // include with Next.js 13+
import { useEffect, useState } from "react"
import { HttpTypes } from "@aiminaabeejs/types"
import { sdk } from "@/lib/sdk"
type Props = {
categoryId: string
}
export default function CategoryProducts({
categoryId,
}: Props) {
const [loading, setLoading] = useState(true)
const [products, setProducts] = useState<
HttpTypes.StoreProduct[]
>([])
const limit = 20
const [currentPage, setCurrentPage] = useState(1)
const [hasMorePages, setHasMorePages] = useState(false)
useEffect(() => {
if (!loading) {
return
}
const offset = (currentPage - 1) * limit
sdk.store.product.list("us", {
limit,
offset,
category_id: categoryId,
})
.then(({ products: dataProducts, count }) => {
setProducts((prev) => {
if (prev.length > offset) {
// products already added because the same request has already been sent
return prev
}
return [
...prev,
...dataProducts,
]
})
setHasMorePages(count > limit * currentPage)
setLoading(false)
})
}, [loading])
return (
<div>
{loading && <span>Loading...</span>}
{!loading && products.length === 0 && (
<span>No products found for category.</span>
)}
{!loading && products.length > 0 && (
<ul>
{products.map((product) => (
<li key={product.id}>{product.title}</li>
))}
</ul>
)}
{!loading && hasMorePages && (
<button
onClick={() => {
setCurrentPage((prev) => prev + 1)
setLoading(true)
}}
disabled={loading}
>
Load More
</button>
)}
</div>
)
}

JS SDK

ts

tsCopy
sdk.store.product.list("us", {
// other query params...
category_id: categoryId,
})
.then(({ products, count }) => {
// use products...
console.log(products)
})

In this example, you retrieve the products that belong to a category by passing the category's ID as a query parameter to the List Products API route. You can also pass other query parameters to filter or paginate the products, such as limit and offset.

The response has a products field, which is an array of products.

To learn more about displaying the products and their variants, refer to the following guides: