Reputation: 31
I'm trying to fetch data from an API in my Next.js app using either getStaticProps() or getServerSideProps(), but the data is not being fetched and displayed in my app. When I use fetch() inside a component, the data is fetched and displayed correctly, but I want to use server-side rendering to improve performance and SEO. Note: I have build my api with laravel and it works when I am using it in postman.
export async function getStaticProps() {
try {
const response = await fetch('http://localhost:8000/api/students');
const { data } = await response.json();
return { props: { students: data } };
} catch (error) {
console.log(error);
return { props: { students: [] } };
}
}
And here's my code for rendering the data in my component:
export default function StudentsPage({ students }) {
return (
<>
<h1>Students</h1>
<ul>
{students.map((student) => (
<li key={student.id}>
{student.name} ({student.email})
</li>
))}
</ul>
</>
);
}
When I load the page, I get the fetch failed and 500 internal server error which there is no error with my api endpoints.
What could be causing this issue, and how can I fix it?
I want to get the list of students comming from my api endpoints using the getStaticProps or getServerSideProps in nextjs.
Upvotes: 2
Views: 5506
Reputation: 273
getStaticProps happens when you build your application.
The data required to render the page is available at build time ahead of a user’s request
So make sure that http://localhost:8000/ is available during that time.
https://nextjs.org/docs/basic-features/data-fetching/get-static-props
Upvotes: 2