mirror of
https://github.com/vercel/commerce.git
synced 2025-07-23 04:36:49 +00:00
feat: implement products infinite loading
Signed-off-by: Chloe <pinkcloudvnn@gmail.com>
This commit is contained in:
109
components/layout/products-list/actions.ts
Normal file
109
components/layout/products-list/actions.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
'use server';
|
||||
|
||||
import {
|
||||
AVAILABILITY_FILTER_ID,
|
||||
PRICE_FILTER_ID,
|
||||
PRODUCT_METAFIELD_PREFIX,
|
||||
VARIANT_METAFIELD_PREFIX,
|
||||
defaultSort,
|
||||
sorting
|
||||
} from 'lib/constants';
|
||||
import { getCollectionProducts, getProducts } from 'lib/shopify';
|
||||
|
||||
const constructFilterInput = (filters: {
|
||||
[key: string]: string | string[] | undefined;
|
||||
}): Array<object> => {
|
||||
const results = [] as Array<object>;
|
||||
Object.entries(filters)
|
||||
.filter(([key]) => !key.startsWith(PRICE_FILTER_ID))
|
||||
.forEach(([key, value]) => {
|
||||
const [namespace, metafieldKey] = key.split('.').slice(-2);
|
||||
const values = Array.isArray(value) ? value : [value];
|
||||
|
||||
if (key === AVAILABILITY_FILTER_ID) {
|
||||
results.push({
|
||||
available: value === 'true'
|
||||
});
|
||||
} else if (key.startsWith(PRODUCT_METAFIELD_PREFIX)) {
|
||||
results.push(
|
||||
...values.map((v) => ({
|
||||
productMetafield: {
|
||||
namespace,
|
||||
key: metafieldKey,
|
||||
value: v
|
||||
}
|
||||
}))
|
||||
);
|
||||
} else if (key.startsWith(VARIANT_METAFIELD_PREFIX)) {
|
||||
results.push(
|
||||
...values.map((v) => ({
|
||||
variantMetafield: {
|
||||
namespace,
|
||||
key: metafieldKey,
|
||||
value: v
|
||||
}
|
||||
}))
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const price = {} as { min?: number; max?: number };
|
||||
|
||||
if (filters[`${PRICE_FILTER_ID}.min`]) {
|
||||
price.min = Number(filters[`${PRICE_FILTER_ID}.min`]);
|
||||
}
|
||||
if (filters[`${PRICE_FILTER_ID}.max`]) {
|
||||
price.max = Number(filters[`${PRICE_FILTER_ID}.max`]);
|
||||
!price.min && (price.min = 0);
|
||||
}
|
||||
if (price.max || price.min) {
|
||||
results.push({ price });
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
export const getProductsInCollection = async ({
|
||||
searchParams,
|
||||
afterCursor
|
||||
}: {
|
||||
searchParams?: {
|
||||
[key: string]: string | string[] | undefined;
|
||||
};
|
||||
afterCursor?: string;
|
||||
}) => {
|
||||
const { sort, q, collection, ...rest } = searchParams as { [key: string]: string };
|
||||
const { sortKey, reverse } = sorting.find((item) => item.slug === sort) || defaultSort;
|
||||
const filtersInput = constructFilterInput(rest);
|
||||
|
||||
const response = await getCollectionProducts({
|
||||
collection: collection as string,
|
||||
sortKey,
|
||||
reverse,
|
||||
...(filtersInput.length ? { filters: filtersInput } : {}),
|
||||
...(afterCursor ? { after: afterCursor } : {})
|
||||
});
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
export const searchProducts = async ({
|
||||
searchParams,
|
||||
afterCursor
|
||||
}: {
|
||||
searchParams?: {
|
||||
[key: string]: string | string[] | undefined;
|
||||
};
|
||||
afterCursor?: string;
|
||||
}) => {
|
||||
const { sort, q: searchValue } = searchParams as { [key: string]: string };
|
||||
const { sortKey, reverse } = sorting.find((item) => item.slug === sort) || defaultSort;
|
||||
|
||||
const response = await getProducts({
|
||||
sortKey,
|
||||
reverse,
|
||||
query: searchValue,
|
||||
...(afterCursor ? { after: afterCursor } : {})
|
||||
});
|
||||
|
||||
return response;
|
||||
};
|
91
components/layout/products-list/index.tsx
Normal file
91
components/layout/products-list/index.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
'use client';
|
||||
|
||||
import Grid from 'components/grid';
|
||||
import { GridTileImage } from 'components/grid/tile';
|
||||
import { Product } from 'lib/shopify/types';
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { getProductsInCollection, searchProducts } from './actions';
|
||||
|
||||
const ProductsList = ({
|
||||
initialProducts,
|
||||
pageInfo,
|
||||
searchParams,
|
||||
page
|
||||
}: {
|
||||
initialProducts: Product[];
|
||||
pageInfo: {
|
||||
endCursor: string;
|
||||
hasNextPage: boolean;
|
||||
};
|
||||
searchParams?: { [key: string]: string | string[] | undefined };
|
||||
page: 'search' | 'collection';
|
||||
}) => {
|
||||
const [products, setProducts] = useState(initialProducts);
|
||||
const [_pageInfo, setPageInfo] = useState(pageInfo);
|
||||
const lastElement = useRef(null);
|
||||
|
||||
useEffect(() => {
|
||||
const lastElementRef = lastElement.current;
|
||||
|
||||
const loadMoreProducts = async () => {
|
||||
const params = {
|
||||
searchParams,
|
||||
afterCursor: _pageInfo.endCursor
|
||||
};
|
||||
const { products, pageInfo } =
|
||||
page === 'collection'
|
||||
? await getProductsInCollection(params)
|
||||
: await searchProducts(params);
|
||||
|
||||
setProducts((prev) => [...prev, ...products]);
|
||||
setPageInfo({
|
||||
hasNextPage: pageInfo.hasNextPage,
|
||||
endCursor: pageInfo.endCursor
|
||||
});
|
||||
};
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries[0]?.isIntersecting) {
|
||||
loadMoreProducts();
|
||||
}
|
||||
},
|
||||
{ threshold: 1 }
|
||||
);
|
||||
lastElementRef && observer.observe(lastElementRef);
|
||||
|
||||
return () => {
|
||||
if (lastElementRef) {
|
||||
observer.unobserve(lastElementRef);
|
||||
}
|
||||
};
|
||||
}, [_pageInfo.endCursor, page, searchParams]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{products.map((product, index) => (
|
||||
<Grid.Item
|
||||
key={product.handle}
|
||||
className="animate-fadeIn rounded-lg"
|
||||
ref={index === products.length - 1 && _pageInfo.hasNextPage ? lastElement : undefined}
|
||||
>
|
||||
<Link className="relative inline-block h-full w-full" href={`/product/${product.handle}`}>
|
||||
<GridTileImage
|
||||
alt={product.title}
|
||||
label={{
|
||||
title: product.title,
|
||||
amount: product.priceRange.maxVariantPrice.amount,
|
||||
currencyCode: product.priceRange.maxVariantPrice.currencyCode
|
||||
}}
|
||||
src={product.featuredImage?.url}
|
||||
fill
|
||||
sizes="(min-width: 768px) 33vw, (min-width: 640px) 50vw, 100vw"
|
||||
/>
|
||||
</Link>
|
||||
</Grid.Item>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductsList;
|
Reference in New Issue
Block a user