Reputation: 18538
Refer to discussion here. I faced similar error. Everything worked fine when fallback
is set to false
. However, when fallback is set to true, next js throws error
throw new Error('Failed to load static props')
Upvotes: 6
Views: 18297
Reputation: 470
Here's how I solved this issue using notFound: true
inside getStaticProps
.
export async function getStaticProps({ params: { id } }) {
const res = await fetch(`{{api}}/items?id=${id}`);
const item = await res.json();
const notFound = item[0] ? false : true;
return {
props: {
item: item[0]
},
revalidate: 10,
notFound
};
}
Upvotes: 1
Reputation: 460
I have found my answer here https://github.com/vercel/next.js/discussions/11862:
Your getStaticProps should return a boolean like
notFound: true
, and your page can render a 404 page or thenext/error
page. This would allow the page to eventually become real (if the missing slug is created in backend).
Upvotes: 1
Reputation: 18538
After lot of searching and trial and error, I found out that the error was because of the exceptions throws inside getStaticProps
.
To solve this issue all I did is to use try-catch block.
export async function getStaticProps({ params }) {
let data = null;
try {
data = await getData(params.slug);
} catch (err) { };
return {
props: {
data,
},
};
And when rendering your can use
if(props.data) return (<your-jsx-here></your-jsx-here>)
else return <div>Any message if you want</div>
Upvotes: 10