What is the purpose of useServerFn, all works without it
At What are Server Functions? page we have example of server function that can be used with
useQuery (from TanStack Query, to fetch data from endpoint).
Example is as follows:
However, if I remove useServerFn and use getServerPosts directly:
Then everything keeps working just as fine. When I inspect natwork requests in dev tools, there's nothing suspicious going on, I mean the requests are the same, payloads returned are also the same, the application itself keeps working fine.
So the question is what is the purpose of useServerFn hooks and what it help us with?Server Functions | TanStack Start React Docs
What are Server Functions? Server functions let you define server-only logic that can be called from anywhere in your application loaders, components, hooks, or other server functions. They run on the...
4 Replies
foreign-sapphire•2mo ago
among other things, it handles redirects
if your server function throws a
redirect, you need useServerFn for the redirection to work. Otherwise it'll be unhandle and just be an errorharsh-harlequinOP•2mo ago
cool, thanks for the explanation! Indeed, with
throw redirect() it works, so what it does, in theory? i mean why for example, redirect does not work without it?foreign-sapphire•2mo ago
because its just client side error catching into handling it as a navigation
you'll ask "but why isnt just returning a 302 instead of an error" ?
Because 302 would cause a refresh
not very good
harsh-harlequinOP•2mo ago
cool thanks for explanations!