#Cache revalidation pattern (load cache / update as soon as data is revalidated)

4 messages · Page 1 of 1 (latest)

merry lodge
#

I have a very slow fetch request that gets executed in the server render process.
So my user looks on the loading screen for a long time.

I would like to cache this request, to have a faster initial load for my page.
However, it is somewhat important that my user actually gets the freshest data.

So what i would like to do is to use cached data on my server side rendering, but in there also initiate a full new fetch request.
The user then gets the cached data at first, but as soon as the fresh fetch is ready the data gets updated.

Are there any good patterns to do so?

I tried:

export const fetchUserReportsCached = unstable_cache(
  fetchUserReports,
  ["user-reports"],
  {
    revalidate: 1,
  },
);

but this does not automatically update the frontend after revalidation.

oak wagonBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

merry lodge
#

Ok when i call router.refresh() on the client, with the fetch like:

export const fetchUserReportsCached = unstable_cache(
  fetchUserReports,
  ["user-reports"],
  {
    revalidate: 1,
  },
);

it somewhat works as expected. But what if the fetch takes even longer and router.refresh() revalidates, before the cache from unstable_cache is even updated?

Or does router.refresh() understand that unstable_cache is still revalidating and waits for it to finish?

clear flower
#

@merry lodge a better way would be, have a server action do the entire data fetching and on it finishing.. revalidate the path you are on with revalidatePath, call this from a useEffect from a client component.