can i use swr with server action?
Answered
Sage Grouse posted this in #help-forum
Sage GrouseOP
is it ok to use swr with server action instead of api route? Lets says i want to fetch some data in client component.Can i do something like this instead of creating api route?
const { data } = useSWR('serverAction', serverAction);Answered by joulev
Don’t use server actions for data fetching. Reason: they cannot be run in parallel
15 Replies
Im not familiar with the useSWR hook, but you can definately use server actions instead of api routes.
does useSWR work client side?
https://www.reddit.com/r/nextjs/comments/18vslhr/fetching_data_using_swr_with_server_components/
this might help answer your question.
this might help answer your question.
You can also use SWR directly with server actions instead of setting up an API. Instead of a fetch request, just refer to a server action and just put some string in the url field.I think it works because all a server action is is a rest request, technically.
Sage GrouseOP
yes i want to use in clinet component
Yeah, principle should still work, give it a shot and see.
As we say at work... WTWTCH 🙂
Sage GrouseOP
it works. but is it valid way of doing it? I suppose if swr is made by vercel it should work, but i did not find any info in theirs docs. is there potential drawbacks or security issues with it?
I couldnt answer that someone else might be able to. I would build it and start and test it while monitoring the network requests in the debug menu
@Sage Grouse is it ok to use swr with server action instead of api route? Lets says i want to fetch some data in client component.Can i do something like this instead of creating api route? `const { data } = useSWR('serverAction', serverAction);`
Don’t use server actions for data fetching. Reason: they cannot be run in parallel
Answer
@joulev Don’t use server actions for data fetching. Reason: they cannot be run in parallel
Sage GrouseOP
What to do instead? Api routes for fetching? Fetching in server components ?
@Sage Grouse What to do instead? Api routes for fetching? Fetching in server components ?
Route handlers + swr (client side fetching) or server components (server side fetching) yes
@joulev Route handlers + swr (client side fetching) or server components (server side fetching) yes
Sage GrouseOP
One more question. If i need to fetch data based on url parameters, i can not access param in server component? My only option is to fetch client side ?