I'm getting the error Generating static pages (0/5)TypeError: Cannot read properties of undefined (reading 'name')
when building my project with next.js.
Code:
Page:
import User from './components/user';
export default function UserList({ users }) {
return (
<>
<h1>List of Users</h1>
{users?.map((user) => (
<User user={user} key={user.id}></User>
))}
</>
);
}
export async function getStaticProps() {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
return {
props: {
users: data,
},
};
}
Component:
export default function User({ user }) {
return (
<>
<p>{user.name}</p>
<p>{user.email}</p>
</>
);
}
So it seems like when pre-rendering the site the first time the API did not load the data yet. The error is fixed by adding this to the component:
export default function User({ user }) {
if (user === undefined) {
return <h1></h1>;
}
return (
<>
<p>{user.name}</p>
<p>{user.email}</p>
</>
);
}
But now I need to add this fix to every component in my project. Is there another fix for this error?
I fount the problem: The components directory was inside the pages directory. With this fixed everything works fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.