Next.js Discord

Discord Forum

Caching GET Requests when using Server Actions

Answered
African Slender-snouted Crocodil… posted this in #help-forum
Open in Discord
African Slender-snouted CrocodileOP
Hi Guys... I wanted to know whether it's possible to cache my data when using server actions cos anytime I move back and forth on my routes... the data is being re-fetched. (Attached is an example of my Server Action setup and custom fetch hook for fetching Categories )
Answered by B33fb0n3
Some things, that you need to change are:
1. Fetch data serverside and (if needed) pass it via props down to the specific location
2. When that's not possible, fetch your route handler on the clientside while using a clientside fetching library. Like this you have full control over your data
3. When you don't have a route handler, you can also fetch via a server action. However, there are some disadvantages.

So please, do 1. or 2. to make sure you won't get data refetches when switching the routes.
View full answer

4 Replies

Since you are doing the fetch in the client side, use unstable cache. wrap your contents of the try block with unstable cache
https://nextjs.org/docs/app/api-reference/functions/unstable_cache
@African Slender-snouted Crocodile Hi Guys... I wanted to know whether it's possible to cache my data when using server actions cos anytime I move back and forth on my routes... the data is being re-fetched. (Attached is an example of my Server Action setup and custom fetch hook for fetching Categories )
Some things, that you need to change are:
1. Fetch data serverside and (if needed) pass it via props down to the specific location
2. When that's not possible, fetch your route handler on the clientside while using a clientside fetching library. Like this you have full control over your data
3. When you don't have a route handler, you can also fetch via a server action. However, there are some disadvantages.

So please, do 1. or 2. to make sure you won't get data refetches when switching the routes.
Answer
African Slender-snouted CrocodileOP
Thank y'all. I'm fetching my data on the server-side now. Thank youuu🙏
happy to help