#When submitting a server action, can you do a partial re-render of the page?

1 messages · Page 1 of 1 (latest)

gentle hare
#

When I do revalidatePath('/foo') in the server action, it has refetch all the data for the page. Is there a way to just invalidate one small part of the page instead?

shell bronzeBOT
#

Hi @gentle hare. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, Next.js provides a way to invalidate a specific part of the data instead of the entire page. This can be achieved by using the revalidateTag function.

When you use fetch, you can tag cache entries with one or more tags. Then, you can call revalidateTag to revalidate all entries associated with that tag. This allows you to invalidate a specific data fetch with a cache tag.

Here is an example of how you can use revalidateTag:

'use server'
 
import { revalidateTag } from 'next/cache'
 
export default async function submit() {
 await addPost()
 revalidateTag('posts')
}

In this example, revalidateTag('posts') will revalidate all data associated with the 'posts' tag.

You can find more information about this in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@gentle hare kapa.ai is still learning and improving, please let us know how it did by reacting below

gentle hare
#

@shell bronze I'm using a third-party library (supabase) to make the API calls, so I don't have access to the options within fetch() to set the tag. How should I do this?

shell bronzeBOT
#

Let me check the knowledge base for you. One moment! :books:

#

In cases where you're using a third-party library that doesn't support or expose fetch (like Supabase, a database, CMS, or ORM client), you can configure the caching and revalidating behavior of those requests using the Route Segment Config Option and React's cache function.

Here's an example of how you can use React's cache function to memoize data requests:

import { cache } from 'react'
 
export const revalidate = 3600 // revalidate the data at most every hour
 
export const getItem = cache(async (id: string) => {
 const item = await db.item.findUnique({ id })
 return item
})

In this example, the getItem function is called twice, but only one query will be made to the database.

However, it's important to note that Next.js is currently working on an API, unstable_cache, for configuring the caching and revalidating behavior of individual third-party requests. You can keep an eye on the Next.js documentation (https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) for updates on this.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: