#How to cache data with server actions

29 messages Β· Page 1 of 1 (latest)

velvet crow
#

Hello everyone, I'm performing my queries using server actions. The process is illustrated in the images below. I know that if you use fetch the data is cached by default, but with server actions this doesnt happend, what should I do?

fading basinBOT
#

πŸ”Ž 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)

steady axle
# velvet crow Hello everyone, I'm performing my queries using server actions. The process is i...

server actions shouldn't be used to fetch data. Technically it is possible, but in the first way they are made to mutate data serverside.
Another thing that you want to use is a clientside fetching library. Without it you can lose control over your data pretty fast. SWR or React Query are examples.
Another thing that you also need to know is that you should fetch data serverside and then pass it via props to the client. That makes your page load faster
To solve your issue: use unstable_cache to cache third party results

velvet crow
#

Anyway, I pass the information to the client component via props since it is wrapped in a <Suspense>, but what I should do is use React Query for queries (selects), and for inserts, deletes, or updates, I can continue using server actions, right?

velvet crow
steady axle
fading basinBOT
velvet crow
steady axle
#

happy to help

strong wagon
#

what worked for me was to have an /api/ endpoint and some helper functions for grabbing the data. Then the requests get cached

velvet crow
velvet crow
#

I added a console.log to the database query, and it executes every time, this indicate that it is not being cached right?

strong wagon
#

you could add your own headers to the req

#

export async function GET(req, { params }) {

try {
const { slug } = await params;
const { article, articleError } = await fetchSingleArticle(slug);
if (articleError) {
return new Response(JSON.stringify({ error: articleError.message }), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}

return new Response(JSON.stringify({ article }), {
  status: 200,
  headers: {
    'Cache-Control': 'public, s-maxage=3600, stale-while-revalidate=59', 
    'Content-Type': 'application/json',
  },
});

} catch (error) {
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: {
'Content-Type': 'application/json',
},
});
}
}

velvet crow
strong wagon
#

export const apiFetchPosts = async ( { category, subcategory, region, search, page, pageSize } ) => {
try {
const req = await fetch(${process.env.NEXT_PUBLIC_BASE_URL}/api/get-public-posts?category=${category}&subcategory=${subcategory}&region=${region}&search=${search}&page=${page}&pageSize=${pageSize}, {
cache: 'force-cache',
next: { tags: ['public-posts'], revalidate: 3600 }
});

    if (!req.ok) {
        throw new Error(`Failed to fetch Regions: ${req.status}`);
    }
    const response = await req.json();
    return response;
} catch (error) {
    console.error('Error fetching regions:', error);
    throw error;
}

};

#

just some mumbo jumbo code, but you get the idea

velvet crow
#

Oh, right, in the URL. Thank you so much! I'll give it a try.

#

yep, now its working finalyyyy

velvet crow
fading basinBOT
strong wagon
#

Indeed, it’s something they changed in nextjs 15. Force cache was on by default in prev versions

velvet crow
#

if the data has to be updated with this it will be do it right?
revalidateTag("user-data");

#

'pubic-posts' (to continue with the same example)

strong wagon
#

This will clear the next cache but you will see the content change after the time you set in the headers expires i think. Try to test it out

velvet crow
#

Yes, it works like that, but I wanted to force an update when the user modifies their data so that the new changes are reflected immediately.

strong wagon
#

i was also searching for that for a long time and couldn/t make it work, at least not when hosting it on vercel

velvet crow
#

for me with the revalidateTag() function is working, i have it in localhost, you think that hosted in vercel it wont work?