To integrate dynamic product data from your API into the ProductSlider component within your Dashboard, you'll need to perform the following steps:
-
Fetch Data on the Server-Side in Dashboard: Utilize Next.js's server-side rendering (SSR) capabilities to fetch the top-selling products from the API.
-
Pass Fetched Data as Props to ProductSlider: After fetching the data, pass it down to the ProductSlider component as props.
-
Update ProductSlider to Receive and Display Dynamic Data: Modify the ProductSlider component to accept the products as props and render them accordingly.
Below are the detailed steps and code implementations for each part.
1. Update the Dashboard Component to Fetch Data Server-Side
Since Dashboard is a server component (it doesn't have the 'use client' directive), you can perform server-side data fetching directly within it. Here's how you can modify the Dashboard component to fetch the top-selling products and pass them to ProductSlider.
Updated Dashboard Component
// app/dashboard/page.jsx or wherever your Dashboard component is located
import dynamic from 'next/dynamic';
import Hero from "@/components/Hero";
import { ProductWithSales } from "@/components/ProductWithSales";
import AsyncNavBar from "@/components/AsyncNavBar";
const ProductSlider = dynamic(() => import('@/components/ProductSlider'), {
// You can add a loading component if desired
suspense: false,
});
const CustomProduct = dynamic(() => import('@/components/CustomProduct'));
const ProductCategorySlider = dynamic(() => import('@/components/ProductCategorySlider'));
const Footer = dynamic(() => import('@/components/Footer'));
export default async function Dashboard() {
// Fetch the top-selling products from the API
const res = await fetch('https://dev.naayiq.com/products/top-selling', {
// It's good practice to cache the response if appropriate
next: { revalidate: 60 }, // Revalidates every 60 seconds
});
if (!res.ok) {
// Handle error appropriately
console.error('Failed to fetch top-selling products');
return <div>Error loading products.</div>;
}
const data = await res.json();
const products = data.products || []; // Ensure products is an array
return (
<div className="overflow-x-hidden">
<AsyncNavBar />
<Hero />
<ProductWithSales />
<ProductSlider products={products} /> {/* Pass products as props */}
<CustomProduct
title="Our New Products"
subtitle="Check out our new products"
description="Keep up to date with our latest products and make your skin glowing."
bigimg="/woman2.webp"
flower="/pingwing.webp"
/>
<ProductCategorySlider />
<Footer />
</div>
);
}
Explanation:
-
Fetching Data: The Dashboard component uses fetch to retrieve the top-selling products from the provided API endpoint. The next: { revalidate: 60 } option ensures that the data is revalidated every 60 seconds, enabling Incremental Static Regeneration (ISR) if you're using Next.js 13 or higher.
-
Error Handling: If the fetch request fails (!res.ok), it logs an error and displays an error message. You can enhance this by providing a more user-friendly error component.
-
Passing Props: The fetched products are passed as props to the ProductSlider component.
2. Modify the ProductSlider Component to Accept Dynamic Props
Next, update the ProductSlider component to receive the products prop and render them dynamically instead of using hardcoded data.
Updated ProductSlider Component
// components/ProductSlider.jsx
'use client'; // Ensure this is a client component
import React, { useRef, useState } from 'react';
import dynamic from 'next/dynamic';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
const Slider = dynamic(() => import('react-slick'), { ssr: false });
import Image from 'next/image';
import Link from "next/link";
const ProductSlider = ({ products }) => { // Receive products as props
const sliderRef = useRef(null);
const [loadedImages, setLoadedImages] = useState({});
// Handle cases where products are less than expected
const sliderProducts = products.length > 0 ? products : [
{
id: 0,
title: 'No Products Available',
description: 'Please check back later.',
minPrice: '0.00 IQD',
image: null,
href: '#',
},
];
const settings = {
dots: true,
infinite: sliderProducts.length > 1, // Disable infinite loop if only one product
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
};
const handleNext = () => {
sliderRef.current.slickNext();
};
const handleImageLoad = (id) => {
setLoadedImages(prev => ({ ...prev, [id]: true }));
};
return (
<>
<div className="flex mb-12 p-4 flex-col justify-center items-center gap-6 w-full h-auto bg-[#F6F3F17F] rounded-lg relative">
<div className="flex justify-between mb-6 items-center w-[95%]">
<h1 className="text-[#201E1C] font-sans font-medium text-3xl mb-6">Best Seller</h1>
<Link prefetch={false} href="/products?sortBy=Best+Selling" className="text-[#3B5345] font-serif text-xl font-medium">Show all</Link>
</div>
<Slider {...settings} ref={sliderRef} className="relative bottom-12 w-full">
{sliderProducts.map((product) => (
<div key={product.id} className="flex flex-col justify-center items-center">
<div className="flex flex-col gap-4 justify-center items-center w-full">
<div className="w-full h-[400px] relative">
{!loadedImages[product.id] && product.image && (
<div className="absolute inset-0 bg-gray-200 animate-pulse rounded-lg" />
)}
{product.image ? (
<Image
src={`https://storage.naayiq.com/resources/${product.image}`}
alt={product.title}
fill
sizes="(max-width: 768px) 100vw,
(max-width: 1200px) 50vw,
33vw"
className={`object-cover rounded-lg ${!loadedImages[product.id] ? 'invisible' : ''}`}
onLoad={() => handleImageLoad(product.id)}
/>
) : (
<div className="flex items-center justify-center h-full bg-gray-200 rounded-lg">
<span className="text-gray-500">No Image Available</span>
</div>
)}
</div>
<div className="flex text-2xl leading-5 font-medium font-serif justify-between w-full items-center">
<h2 className="mt-4 min-h-12 ml-2 max-w-52">{product.title}</h2>
<p className="mt-2 min-h-12 self-end">{product.minPrice.toLocaleString()} IQD</p>
</div>
<Link
href={`/products/${product.id}`} // Assuming 'href' refers to product ID
className="w-full text-center mb-6 py-1 mt-4 rounded-full font-serif text-2xl bg-[#3B5345] text-white">
Add To Cart
</Link>
</div>
</div>
))}
</Slider>
{sliderProducts.length > 1 && (
<button
onClick={handleNext}
className="absolute font-serif text-xl little-white bottom-[40%] right-6 px-2 py-2 border border-[#695C5C] rounded-[20px]"
>
<span>Swipe </span>
<Image src="/resources/nextArrow.svg" alt="next" width={24} height={24} className="inline" />
</button>
)}
</div>
<div className="absolute transform -translate-y-14 left-4">
<svg width="35" height="35" viewBox="0 0 46 46" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M21.0413 2.48763C21.4805 0.360124 24.5195 0.360135 24.9587 2.48765L27.8676 16.5781C28.029 17.36 28.64 17.971 29.4219 18.1324L43.5124 21.0413C45.6399 21.4805 45.6399 24.5195 43.5124 24.9587L29.4219 27.8676C28.64 28.029 28.029 28.64 27.8676 29.4219L24.9587 43.5124C24.5195 45.6399 21.4805 45.6399 21.0413 43.5124L18.1324 29.4219C17.971 28.64 17.36 28.029 16.5781 27.8676L2.48763 24.9587C0.360124 24.5195 0.360135 21.4805 2.48765 21.0413L16.5781 18.1324C17.36 17.971 17.971 17.36 18.1324 16.5781L21.0413 2.48763Z"
fill="#4F463D" />
</svg>
</div>
</>
);
};
export default ProductSlider;
Key Changes and Explanations:
-
Receiving products as Props:
- The
ProductSlider component now accepts a products prop, which should be an array of product objects fetched from the API.
const ProductSlider = ({ products }) => { /* ... */ };
-
Handling Dynamic Data:
- Instead of using hardcoded products, the component now uses the
products prop to dynamically generate the slider items.
- It also ensures that if no products are available, a placeholder message is displayed.
const sliderProducts = products.length > 0 ? products : [
{
id: 0,
title: 'No Products Available',
description: 'Please check back later.',
minPrice: 0.00,
image: null,
href: '#',
},
];
-
Conditional Infinite Loop:
- The slider will only loop infinitely if there is more than one product.
infinite: sliderProducts.length > 1,
-
Image Handling:
- The
Image component now dynamically constructs the image URL based on the image field from the product data.
- It also handles cases where the image may be
null by displaying a placeholder.
src={`https://storage.naayiq.com/resources/${product.image}`}
-
Dynamic Link Construction:
- The
href prop in the Link component is assumed to be the product ID. Ensure this aligns with your routing structure.
href={`/products/${product.id}`}
-
Conditional Rendering of 'Swipe' Button:
- The 'Swipe' button is only displayed if there is more than one product to navigate through.
{sliderProducts.length > 1 && (
<button /* ... */ >
{/* ... */}
</button>
)}
-
Improved Price Display:
- Formats the
minPrice using toLocaleString for better readability.
{product.minPrice.toLocaleString()} IQD
3. Additional Recommendations
-
Data Validation: Ensure that the data fetched from the API matches the expected structure. You might want to implement additional checks or use TypeScript interfaces to enforce data types.
-
Loading States: While Dashboard fetches data server-side, consider adding a loading state or skeleton UI if the ProductSlider component takes time to hydrate on the client.
-
Error Handling: Enhance error handling both in the Dashboard and ProductSlider components to provide better user feedback in case of failures.
-
Caching Strategies: Depending on how frequently the top-selling products change, adjust the revalidate time to balance between data freshness and performance.
-
Responsive Design: Ensure that the ProductSlider is responsive across different device sizes. The current sizes prop in the Image component is set for responsiveness, but test it thoroughly.
By following these steps, your Dashboard will dynamically fetch the top-selling products from your API and display them seamlessly within the ProductSlider component. This approach ensures that the data remains up-to-date and leverages Next.js's powerful SSR capabilities for optimal performance.