converted products page into server side.

This commit is contained in:
Amritanshu Agrawal 2024-10-17 09:15:34 +05:30
parent 0deee17031
commit d4373138fa

View File

@ -1,40 +1,33 @@
'use client';
import { HttpTypes } from '@medusajs/types';
// import Image from 'next/image';
import Link from 'next/link';
import { useEffect, useState } from 'react';
// import { useEffect, useState } from 'react';
export default function ProductsPage() {
const [loading, setLoading] = useState(true);
async function fetchProducts() {
const params = new URLSearchParams({
fields: `*variants.prices.*`,
region_id: process.env.NEXT_PUBLIC_DEFAULT_REGION_ID as string,
});
const [products, setProducts] = useState<HttpTypes.StoreProduct[]>([]);
const response = await fetch(`${process.env.NEXT_PUBLIC_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,
},
});
useEffect(() => {
if (!loading) {
return;
}
const params = new URLSearchParams({
// fields: `*variants.calculated_price`,
fields: `*variants.prices.*`,
region_id: process.env.NEXT_PUBLIC_DEFAULT_REGION_ID as string,
});
console.log('url: ', `${process.env.NEXT_PUBLIC_BASE_URL}/store/products?${params}`);
fetch(`${process.env.NEXT_PUBLIC_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,
},
})
.then((res) => res.json())
.then((data) => data.products)
.then((data) => {
setProducts(data);
setLoading(false);
});
}, [loading]);
if (!response.ok) {
console.error('Failed to fetch products:', response.statusText);
return [];
}
const data = await response.json();
return data.products;
}
export default async function ProductsPage() {
const products: HttpTypes.StoreProduct[] = await fetchProducts();
return (
<div className='container mx-auto py-12 pt-28'>
{/* Products Grid */}