getStaticProps() and live data working both on the same page? #23096
Unanswered
KennethKinLum
asked this question in
Show and tell
Replies: 1 comment
-
Hey! You are right, page with For example I would use your code :) export default function Home({ initialData }) {
const [data, setData] = useState(initialData);
return (
<div className="Home">
<main>
<Weather data={data} />
</main>
</div>
);
}
export async function getStaticProps() {
const initialData = await fetch("https://api.weather.gov/gridpoints/MTR/84,105/forecast").then((res) => res.json());
return {
props: { initialData },
revalidate: 5 * 60 // tells to Next.js page should be regenerated every 5 minutes
};
} Or you can combine two approaches and do it like this: export default function Home({ initialData, updatedAt }) {
const [data, setData] = useState(initialData);
useEffect(() => {
if (Date.now() - updatedAt < 2 * 60 * 1000) { // data older than two minutes
fetch("https://api.weather.gov/gridpoints/MTR/84,105/forecast")
.then((res) => res.json())
.then((d) => setData(d));
}
}, [updatedAt])
return (
<div className="Home">
<main>
<Weather data={data} />
</main>
</div>
);
}
export async function getStaticProps() {
const initialData = await fetch("https://api.weather.gov/gridpoints/MTR/84,105/forecast").then((res) => res.json());
return {
props: { initialData, updatedAt: Date.now() },
revalidate: 5 * 60 // tells to Next.js page should be regenerated every 5 minutes
};
} The best way, in my opinion, is using |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
It seems that
getStaticProps()
is meant to make static pages actually?But it seems the method below, we can have a static page, that is good for search engine pulling our page content, but at the same time, let the live data override the static data, in a way, best of both world?
Demo: https://codesandbox.io/s/quirky-zhukovsky-l7wb9?file=/pages/index.js
Beta Was this translation helpful? Give feedback.
All reactions