I’m trying to add category filtering to my Shopify store but running into issues. Users should be able to click buttons to filter items by category type.
Here’s my API helper file utils/shopify-api.js:
export async function fetchCollectionItems() {
const query = `
{
collectionByHandle(handle: "homepage") {
title
products(first: 30) {
edges {
node {
id
title
productType
handle
}
}
}
}
}`
const result = await ShopifyAPI(query)
const items = result.data.collectionByHandle.products.edges ? result.data.collectionByHandle.products.edges : []
return items
}
export function filterByCategory(category) {
let filtered = fetchCollectionItems().filter(item => item.node.productType === category);
return filtered;
}
I also have a function to get all categories:
export async function getAllCategories() {
const query =
`{
shop {
products(first:200, query:"-product_type:''") {
edges {
node {
productType
}
}
}
}
}`
const result = await ShopifyAPI(query)
const categories = result.data.shop.products ? result.data.shop.products.edges : []
const uniqueCategories = Array.from(new Set(categories));
return uniqueCategories
}
My main component store.js renders the filter buttons:
import { fetchCollectionItems, getAllCategories, filterByCategory } from "../utils/shopify-api"
import React, { useState, useEffect } from "react";
export default function Store({ items, categories }) {
const [filteredItems, setFilteredItems] = useState(null);
useEffect(() => {
setFilteredItems(fetchCollectionItems());
}, []);
function handleFilter(e) {
let selectedType = e.target.value;
selectedType !== "all"
? setFilteredItems(filterByCategory(selectedType))
: setFilteredItems(fetchCollectionItems());
}
return (
<div>
<div>
{categories &&
categories.map((cat, idx) => (
<button className="filter-btn" key={idx} value={cat.node.productType} onClick={handleFilter}>
{cat.node.productType}
</button>
))}
{filteredItems &&
filteredItems.map(item => (
<div key={item.node.id}>
<h3>{item.node.title}</h3>
</div>
))}
</div>
</div>
)
}
export async function getStaticProps() {
const items = await fetchCollectionItems()
const categories = await getAllCategories()
return {
props: {
items,
categories,
},
}
}
When I click the filter buttons I get this error: TypeError: fetchCollectionItems(...).filter is not a function
How can I fix this filtering functionality? The buttons should filter the displayed products when clicked.