import { GetServerSideProps, NextPage } from 'next';
import Image from 'next/image';
import React from 'react';
import photo from '../../assets/photo.jpg';
type Products = {
data?: {
id: number;
title: string;
body: string;
}[];
};
const defaultProducts: Products = {
data: [],
};
const ExploreProducts: NextPage<Products> = ({ data = defaultProducts.data }) => {
console.log(data);
return (
<div>
<div className='grid grid-cols-12 gap-5'>
{data?.map(product => (
<div className="card w-96 bg-base-100 shadow-xl" key={product.id}>
<figure className="px-10 pt-10">
<Image src={photo} alt="Shoes" className="rounded-xl" />
</figure>
<div className="card-body items-center text-center">
<h2 className="card-title">{product.title}</h2>
<p>{product.body}</p>
<div className="card-actions">
<button className="btn btn-primary">Buy Now</button>
</div>
</div>
</div>
))}
</div>
</div>
);
};
export const getServerSideProps: GetServerSideProps<Products> = async () => {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts");
const data = await response.json();
console.log(data); // Verify that data is being fetched correctly
return {
props: {
data,
},
};
} catch (error) {
console.error(error);
return {
props: {
data: [],
},
};
}
};
export default ExploreProducts;
This is my whole component I am trying fetch data from jsonplaceholder but data is undefined or array is 0. I can’t understand what is problem in this code. I am try to fetch data from the api. but I got undefined data or array is 0. I do not understand what is happening. What problem in my code. Please review this code and tell me what is problem in this code.
I am expecting data from the API want to show in UI.
2
Answers
Your code is right, no issues with your code, just work fine.
I tried in GitHub codespaces just works fine. refer to the below SS.
You’ll have to create a state to manage the data you’re getting and set the state from the fetch. Afterwards, you can pass it down as props to the children components. I prefer to use axios to fetch data.