Next.js Discord

Discord Forum

When using time-base revalidation, how to get the refresh data with the first request?

Answered
Louisiana Waterthrush posted this in #help-forum
Open in Discord
Louisiana WaterthrushOP
more than the specific revalidate seconds, when a request comes, nextjs just return the stale data immediately and fetch the fresh data, then update the cache.

because of that, user need to refresh twice even the duration is more that the revalidate seconds. This is not good for some scenarios. I want a time based revalidation but how to make user get fresh data with only one refresh?
Answered by joulev
try
import { unstable_cache } from "next/cache";

async function getData() {
  const revalidate = 10;
  // This `key` will change every 10 seconds
  const key = Math.floor(new Date().valueOf() / (1000 * revalidate)).toString();
  return unstable_cache(async () => {
    // await db.select().from(...)
    await new Promise((resolve) => setTimeout(resolve, 2000));
    return new Date().toISOString();
  }, [key])();
}

export default async function Page() {
  const data = await getData();
  return <div>{data}</div>;
}

// Make the page dynamic, so that getData() always get called.
// Only the getData() gets called every request, the expensive data query is cached.
export const revalidate = 0;

i'll also post in the linked github thread
View full answer

2 Replies

Louisiana WaterthrushOP
@Louisiana Waterthrush more than the specific revalidate seconds, when a request comes, nextjs just return the stale data immediately and fetch the fresh data, then update the cache. because of that, user need to refresh twice even the duration is more that the revalidate seconds. This is not good for some scenarios. I want a time based revalidation but how to make user get fresh data with only one refresh?
try
import { unstable_cache } from "next/cache";

async function getData() {
  const revalidate = 10;
  // This `key` will change every 10 seconds
  const key = Math.floor(new Date().valueOf() / (1000 * revalidate)).toString();
  return unstable_cache(async () => {
    // await db.select().from(...)
    await new Promise((resolve) => setTimeout(resolve, 2000));
    return new Date().toISOString();
  }, [key])();
}

export default async function Page() {
  const data = await getData();
  return <div>{data}</div>;
}

// Make the page dynamic, so that getData() always get called.
// Only the getData() gets called every request, the expensive data query is cached.
export const revalidate = 0;

i'll also post in the linked github thread
Answer