65 lines
2.2 KiB
TypeScript
65 lines
2.2 KiB
TypeScript
'use client';
|
||
|
||
import { useState, useEffect } from 'react';
|
||
import { useSearchParams, usePathname } from 'next/navigation';
|
||
import ProductCard from '@/components/productcard';
|
||
import ClientPagination from './pagination';
|
||
|
||
export default function ProductGrid({ products }: { products: any[] }) {
|
||
const searchParams = useSearchParams();
|
||
const pathname = usePathname();
|
||
|
||
// ۱. گرفتن شماره صفحه از URL در زمان لود اولیه
|
||
const initialPage = Number(searchParams.get('page')) || 1;
|
||
const [currentPage, setCurrentPage] = useState(initialPage);
|
||
|
||
const limit = 12;
|
||
// محاسبه کل صفحات
|
||
const totalPages = Math.ceil(products.length / limit);
|
||
|
||
// ۲. تابعی برای تغییر همزمان State و آدرس URL
|
||
const handlePageChange = (page: number) => {
|
||
setCurrentPage(page);
|
||
|
||
// تغییر آدرس مرورگر بدون رفرش و بدون درگیر کردن سرور
|
||
const params = new URLSearchParams(searchParams.toString());
|
||
params.set('page', page.toString());
|
||
window.history.pushState(null, '', `${pathname}?${params.toString()}`);
|
||
};
|
||
|
||
// اگر کاربر با دکمههای Back/Forward مرورگر جابجا شد، state آپدیت شود
|
||
useEffect(() => {
|
||
const pageFromUrl = Number(searchParams.get('page')) || 1;
|
||
setCurrentPage(pageFromUrl);
|
||
}, [searchParams]);
|
||
|
||
// برش دادن محصولات فقط در سمت کلاینت
|
||
const startIndex = (currentPage - 1) * limit;
|
||
const endIndex = startIndex + limit;
|
||
const paginatedProducts = products.slice(startIndex, endIndex);
|
||
|
||
if (products.length === 0) {
|
||
return (
|
||
<div className="text-center py-12 bg-gray-50 rounded-lg text-gray-500">
|
||
محصولی یافت نشد.
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<>
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
|
||
{paginatedProducts.map((product: any) => (
|
||
<ProductCard key={product.id} product={product} />
|
||
))}
|
||
</div>
|
||
|
||
<ClientPagination
|
||
totalPages={totalPages}
|
||
currentPage={currentPage}
|
||
onPageChangeAction={handlePageChange}
|
||
/>
|
||
</>
|
||
);
|
||
}
|