'Next's getStaticProps is not returning props in production
I am trying to use Next js's getStaticProps to fetch data from an API and display it. When I test my app locally, the website shows the data from the API, but when I push it to production (AWS Amplify), I am getting not rendering of the data. I am not sure why this is the case.
When my code runs in the browser, it is stuck on the Loading... text and the data never appears.
Here is a link to the live production site
Here is my code:
export default function Park({parkInfo}) {
// only render the data from the API once it has loaded
if (parkInfo) {
const {
name,
description
} = parkInfo
return (
<>
<h1>{name}</h1>
<h1>{description}</h1>
</>
)
// while the data is loading, show a loading text
} else {
return <div>Loading...</div>
}
}
export async function getStaticPaths() {
return {
paths: [],
fallback: true,
}
}
export async function getStaticProps({params}) {
// Set the base URL for the API
const URL = 'https://developer.nps.gov/api/v1/'
// Set data to null to handle errors
let parkInfo = null
const reqBody = {
method: 'GET',
headers: {
Accept: 'application/json, text/plain, */*',
'User-Agent': '*',
},
}
// Call API Data for /PARK
try {
const parkData = await fetch(
`${URL}parks?parkCode=${params?.parkCode}&limit=465&api_key=${process.env.API_KEY}`,
reqBody
)
parkInfo = await parkData.json()
parkInfo = parkInfo?.data[0]
// only send the necessary data to the front end
parkInfo = {
name: parkInfo?.name,
description: parkInfo?.description,
}
} catch (err) {
console.error(err)
}
return {
props: {
parkInfo,
},
revalidate: 86400, // revalidate once per day
}
}
I am not getting an errors in the console because I've caught them with the conditional statement in the return above in the jsx.
I've also used this solution, but I am still unable to return live data in the production site.
Solution 1:[1]
You need to use getServerSideProps instead of getStaticProps.getStaticProps is for static site generation. Its return value is fixed at build time.
See this documentation: https://nextjs.org/docs/basic-features/data-fetching/get-static-props
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mythosil |
