Next.js Discord

Discord Forum

Serving stale content until new content is ready using `fetch("...", { next: { revalidate: ... } })`

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hi,

I have a pretty simple web application, where one of the components relies on data from a server. I would like this to be revalidated every X seconds.
// MyComponent.tsx
async function fetchData(): Promise<Data> {
    const response = await fetch("...", { next: { revalidate: 60 } });
    // do some stuff with the response
    return data;
}

export default async function MyComponent() {
    const data = await fetchData();
    return <p>{data.whatever}</p>
}

// page.tsx
export default function Page() {
    return (
        <Suspense fallback={<p>loading...</p>}>
            <MyComponent />
        </Suspense>
    );
}


This works, for the most part. The user will be shown a cached response if they make a request within 60 seconds of the first fetch.

It doesn't really work how I would like for users who may be the one to trigger the revalidation however. If I am the first user to request once the cache has expired, I will still be sent the old content, and not receive the new content after the request has completed.

I would like for the user to receive the stale content at first, and once the fetch has completed, for the new content to be shown. This is not the case currently as the user will have to refresh after they trigger the revalidation to see the new content, which is expected as far as I'm aware.

2 Replies

Cape lionOP
This is the only way I can think of fixing this:
- Make MyComponent a client component
- Pass some cached data as a prop
- Make the client component do fetch to an API route in order to get the new data
- The app stores the latest data returned in the API route to be used on the next request
@Cape lion This is the only way I can think of fixing this: - Make `MyComponent` a client component - Pass some cached data as a prop - Make the client component do `fetch` to an API route in order to get the new data - The app stores the latest data returned in the API route to be used on the next request
yes, that's exactly how it should be fixed.

server components terminate when they return the component. the connection drops there. so when the updated data comes, it cannot go to the client because the connection is no longer there.

client-side data fetching with swr/react-query is how you can overcome that restriction.