Made the product detail page server side.
This commit is contained in:
parent
c14bceec09
commit
1c2abef4b0
@ -3,80 +3,23 @@
|
||||
import { HttpTypes } from '@medusajs/types';
|
||||
import { ShoppingCart, Star } from 'lucide-react';
|
||||
import Image from 'next/image';
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||
import { useCart } from '@/providers/cart';
|
||||
import { useRegion } from '@/providers/region';
|
||||
|
||||
interface ProductDetailsProps {
|
||||
handle: string;
|
||||
product: HttpTypes.StoreProduct;
|
||||
}
|
||||
|
||||
const ProductDetails: FC<ProductDetailsProps> = ({ handle }) => {
|
||||
export default function ProductDetails({ product }: ProductDetailsProps) {
|
||||
const [quantity, setQuantity] = useState(1);
|
||||
const [product, setProduct] = useState<HttpTypes.StoreProduct | null>();
|
||||
const [selectedVariant, setSelectedVariant] = useState<HttpTypes.StoreProductVariant | null>(null);
|
||||
const [selectedVariant, setSelectedVariant] = useState<HttpTypes.StoreProductVariant>();
|
||||
|
||||
const [isLoading, setIsLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<unknown>(null);
|
||||
|
||||
const { region } = useRegion();
|
||||
const { cart, addToCart } = useCart();
|
||||
|
||||
useEffect(() => {
|
||||
if (!region || !cart) {
|
||||
return;
|
||||
}
|
||||
const fetchProduct = async () => {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
handle: handle,
|
||||
fields: `*variants.calculated_price`,
|
||||
region_id: region?.id as string,
|
||||
});
|
||||
const products: HttpTypes.StoreProduct[] = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_STORE_URL}/store/products?${params}`,
|
||||
{
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-publishable-api-key': process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY as string,
|
||||
},
|
||||
},
|
||||
)
|
||||
.then((res) => res.json())
|
||||
.then((data) => data.products);
|
||||
|
||||
if (products && products.length) {
|
||||
setProduct(products[0]);
|
||||
setSelectedVariant(products[0].variants?.[0] || null);
|
||||
} else {
|
||||
setProduct(null);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
setError(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
fetchProduct();
|
||||
}, [handle, region, cart]);
|
||||
|
||||
if (!region || isLoading) {
|
||||
return <div>Loading...</div>; // Or a skeleton/loading component
|
||||
}
|
||||
if (error) {
|
||||
console.log('Something went wrong error: ', error);
|
||||
return <div>Something went wrong</div>;
|
||||
}
|
||||
|
||||
if (!product) {
|
||||
return <div>Product not found.</div>;
|
||||
}
|
||||
const { addToCart } = useCart();
|
||||
|
||||
return (
|
||||
<div className='px-4 py-8 pt-28'>
|
||||
@ -112,15 +55,18 @@ const ProductDetails: FC<ProductDetailsProps> = ({ handle }) => {
|
||||
</div>
|
||||
<span className='ml-2 text-sm text-gray-600'>(128 reviews)</span>
|
||||
</div>
|
||||
<p className='text-2xl font-bold mb-4'>${selectedVariant?.calculated_price?.calculated_amount?.toFixed(2)}</p>
|
||||
<p className='text-2xl font-bold mb-4'>₹{selectedVariant?.calculated_price?.calculated_amount?.toFixed(2)}</p>
|
||||
<p className='text-gray-600 mb-6'>{product.description}</p>
|
||||
|
||||
<div className='mb-6'>
|
||||
<h3 className='text-lg font-semibold mb-2'>Choose Variant:</h3>
|
||||
<RadioGroup
|
||||
defaultValue={selectedVariant?.id}
|
||||
defaultValue={product.variants?.[0].id}
|
||||
onValueChange={(value) =>
|
||||
setSelectedVariant(product.variants?.find((v) => v.id === value) || product.variants?.[0] || null)
|
||||
setSelectedVariant(
|
||||
product.variants?.find((v) => v.id === value) ||
|
||||
(product.variants?.[0] as HttpTypes.StoreProductVariant),
|
||||
)
|
||||
}
|
||||
>
|
||||
{product.variants?.map((variant) => (
|
||||
@ -205,6 +151,4 @@ const ProductDetails: FC<ProductDetailsProps> = ({ handle }) => {
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductDetails;
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
// import { HttpTypes } from '@medusajs/types';
|
||||
import { FC } from 'react';
|
||||
import { HttpTypes } from '@medusajs/types';
|
||||
|
||||
import ProductDetails from './ProductDetails';
|
||||
|
||||
@ -8,35 +7,50 @@ interface ProductPageProps {
|
||||
handle: string;
|
||||
};
|
||||
}
|
||||
// export async function generateStaticParams() {
|
||||
// // Fetch the list of products
|
||||
// const products: HttpTypes.StoreProduct[] = await fetch(`${process.env.NEXT_PUBLIC_STORE_URL}/store/products`, {
|
||||
// credentials: 'include',
|
||||
// headers: {
|
||||
// 'Content-Type': 'application/json',
|
||||
// 'x-publishable-api-key': process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY as string,
|
||||
// },
|
||||
// })
|
||||
// .then((res) => res.json())
|
||||
// .then((data) => data.products);
|
||||
|
||||
// if (!products) {
|
||||
// return [];
|
||||
// }
|
||||
// // Generate static params based on product handles
|
||||
// const staticParams = products.map((product) => ({
|
||||
// handle: product.handle,
|
||||
// }));
|
||||
// return staticParams;
|
||||
// }
|
||||
async function fetchProduct(handle: string, region: HttpTypes.StoreRegion | undefined) {
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
handle: handle,
|
||||
fields: `*variants.calculated_price`,
|
||||
region_id: region?.id || (process.env.NEXT_PUBLIC_DEFAULT_REGION_ID as string),
|
||||
});
|
||||
const response = await fetch(
|
||||
// const products: HttpTypes.StoreProduct[] = await fetch(
|
||||
`${process.env.NEXT_PRIVATE_BASE_URL}/store/products?${params}`,
|
||||
{
|
||||
credentials: 'include',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-publishable-api-key': process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY as string,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const ProductPage: FC<ProductPageProps> = ({ params }) => {
|
||||
if (!response.ok) {
|
||||
console.error('Failed to fetch product:', response.statusText);
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (!data.products || !data.products.length) {
|
||||
console.error('No products found');
|
||||
return null;
|
||||
}
|
||||
return data.products[0];
|
||||
} catch (error) {
|
||||
console.error('Error fetching product:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default async function ProductPage({ params }: ProductPageProps) {
|
||||
// const { region } = useRegion();
|
||||
const { handle } = params; // Extract the handle from the params
|
||||
const product: HttpTypes.StoreProduct = await fetchProduct(handle, undefined);
|
||||
|
||||
return (
|
||||
// Render the client component and pass necessary props
|
||||
<ProductDetails handle={handle} />
|
||||
<ProductDetails product={product} />
|
||||
);
|
||||
};
|
||||
|
||||
export default ProductPage;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user