Revalidate doesn't work on Vercel using NextJS [duplicate]
Asked Answered
T

1

8

I used the provided example from Vercel documentation, to fetch the data from MongoDB after every 15 seconds, but unfortunately the function doesn't work. What should I do to make it work as expected?

export async function getStaticProps() {
  const allData = getSortedData();

  const client = await clientPromise;
  const isConnected = await client.isConnected();
  const alerts = await client.db()
    .collection("alerts")
    .find({})
    .limit(6)
    .toArray();
  const alertsData = JSON.parse(JSON.stringify(alerts));

  return {
    props: {
      allData,
      isConnected,
      alertsData
    },
    revalidate: 15,
  };
}
Twoup answered 23/10, 2021 at 10:14 Comment(2)
Keep in mind that revalidation doesn't happen automatically after the 15 seconds have passed. A request to that page needs to happen to trigger the revalidation on the server. See this related question: How does the revalidate process in Incremental Static Regeneration work?.Fledgy
useSWR to revalidate data. Here is link to docs: SWR documentationCamber
S
2

So revalidate doesn't just fetch new data every 15 seconds. It generates the page at build time, serves it as static content from cache and then waits for the next user to trigger a new build. The first time the new user triggers a build he/she will be shown a stale page. Then in the background the new page will be generated and served to the next user refreshing the certain webpage.

Here is a quick video with timestamp from Lee Robinson explaining it. https://youtu.be/nrfuN_Hyd3Y?t=112

I hope this makes things more clear for you!

Skeet answered 23/10, 2021 at 11:14 Comment(2)
Yes, exactly. That's what I would like to achieve. Where's the problem in the code? I don't get it.Twoup
Code looks fine, are you sure the data has changed? (Fyi revalidation only works when you build and start the app. In dev mode it just server renders it)Skeet

© 2022 - 2024 — McMap. All rights reserved.