It’s only been a few days since I started learning next.js
. As for now, I can’t figure out how to fetch
data from api
. In plain react
, I used useState
and useEffect
to control and fetch
data. But what about next.js 13.4
?
import { ProductType } from '../Types/productTypes';
import Image from 'next/image';
async function getData() {
const res = await fetch('https://dummyjson.com/products');
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}
export default async function ProductPage() {
const data: ProductType[] = await getData()
return (
<main>
{data.map((product) => (
<div key={product.id} className='border p-4'>
<h3 className='text-xl font-semibold'>{product.title}</h3>
<p className='text-gray-500'>${product.price}</p>
<Image src={product.thumbnail} alt={product.title} className='mt-4 mb-2 w-full h-48 object-contain' />
<button className='bg-blue-500 hover:bg-blue-600 text-white py-2 px-4 rounded'>More details</button>
</div>
))}
</main>
);
}
My type is next:
export type ProductType = {
id: number;
title: string;
description: string;
price: number;
discountPercentage: number;
rating: number;
stock: number;
brand: string;
category: string;
thumbnail: string;
images: string[];
};
2
Answers
I’d like to help but it’s not quite clear what your problem is. Could you expand your question to explain what you’re expecting/what’s not working?
Edit: If you check the structure of your response you’ll see that its type is like this:
You can add this as a return type of your
getData
function:And then map over
data.products
instead ofdata
(which is not an array).In
nextjs 13
by default every component is a server component which mean server component renders on server.if you need to use
useState
useEffect
useRef
etc, you should markuse client
top in the component.You should call your function this way…
Update Your Type
You need to update your type with this …
Just add square bracket in the last.
In React Component