I am working on Next js and i am trying to fetching record via api, but right now i am getting following error
"Cannot read property 'map' of undefined"
Here is my code (components/Blog.jsx)
export default function Blog({ people }) {
return (
<div>
{people.map(person => (
<>
<h1>{person.name}</h1>
<h2>Website: {person.website}</h2>
Email: <code>{person.email}</code>
</>
))}
</div>
);
};
export const getStaticProps = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const people = await response.json();
return {
props: {
people
}
};
};
A possible fix is to before you return your Blog() function you do something like this
people = people || []
This will make people have a default so that it cannot be undefined when you try to map it
After reading your problem, I understood that It happens either because of the undefined value of people
export default function Blog({ people }) {
return (
<div>
{people.map(person => (
<>
<h1>{person.name}</h1>
<h2>Website: {person.website}</h2>
Email: <code>{person.email}</code>
</>
))}
</div>
);
};
export const getStaticProps = async () => {
try{
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const people = await response.json();
return { props: { people} }
}catch{
return { props: { } }
}
};