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,
  };
}
user3630024
  • 111
  • 1
  • 8
  • 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?](https://stackoverflow.com/questions/67077408/how-does-the-revalidate-process-in-incremental-static-regeneration-work). – juliomalves Oct 23 '21 at 15:17
  • useSWR to revalidate data. Here is link to docs: [SWR documentation](https://swr.vercel.app/docs/getting-started) – anolan23 Oct 23 '21 at 15:20

1 Answers1

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!

Wesley Janse
  • 1,244
  • 1
  • 7
  • 14
  • Yes, exactly. That's what I would like to achieve. Where's the problem in the code? I don't get it. – user3630024 Oct 23 '21 at 14:00
  • 2
    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) – Wesley Janse Oct 23 '21 at 14:34