Next.js Discord

Discord Forum

Revalidating router cache (v14.1.2)

Unanswered
Koolie posted this in #help-forum
Open in Discord
KoolieOP
Let's say I have two pages that fetch data using RSC.

First page /[slug]
It's using no-store because data are changed often.
async function getCourse(slug: string): Promise<CourseType | GenericError> {
    const nextCookies = cookies()

    let course

    try {
        const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/course/${slug}`, {
            cache: 'no-store',
            headers: {
                Cookie: `${COOKIE_TOKEN_NAME}=${nextCookies.get(COOKIE_TOKEN_NAME)?.value}`,
            },
            next: {
                tags: ['course'],
            },
        })

        if (res.status === 404) {
            notFound()
        }

        course = await res.json()
    } catch (e) {
        course = {
            exception: e,
        }
    }

    return course
}

Second page /[slug]/edit
The request is the same as above except it's calling another API route and it's tag is course.edit and not course, but it is also using no-store.

Both route are 'using' the same database entity. The first route is displaying the entity, the second one allows the user to edit it using websockets.

The problem
1. The user goes to /[slug], it makes the api call and stores the data in the cache router (as mentionned in the docs)
2. The user edit the page in /[slug]/edit, it makes the second api call and also stores the data in the cache router.
3. The user now goes back to /[slug] to see the changes he just made. He is navigating through a <Link/> that is in the /[slug]/edit page.
4. Once in /[slug], since the data is in the cache router, the page shows the old data, without the changes the user just made.

1 Reply

KoolieOP
My question is, how can i use router.refresh() or revalidateTag() to force /[slug] to force a new api call.

I tried replacing the <Link/> by a button calling this function :
// /[slug]/edit page.tsx (server component)
async function revalidate() {
    'use server'
    revalidateTag('course')
}

// /[slug]/edit file (client component)
function seeCourse() {
    revalidate() // revalidate is coming from props
    router.push(`/${slug}`)
}