T
TanStack5mo ago
wise-white

How to handle throw redirect() from server functions when using ensureQueryData?

I have a server function defined like this:
export const getCurrentUserFn = createServerFn({ method: "GET" }).handler(
async () => {
throw redirect({ to: "/" });
},
);
export const getCurrentUserFn = createServerFn({ method: "GET" }).handler(
async () => {
throw redirect({ to: "/" });
},
);
I'm using it in my route like this:
const currentUserOptions = () =>
queryOptions({
queryKey: ["current-user"],
queryFn: getCurrentUserFn,
});

export const Route = createFileRoute("/url")({
component: RouteComponent,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(currentUserOptions());
},
});
const currentUserOptions = () =>
queryOptions({
queryKey: ["current-user"],
queryFn: getCurrentUserFn,
});

export const Route = createFileRoute("/url")({
component: RouteComponent,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(currentUserOptions());
},
});
The problem is that the redirection thrown from the server function (throw redirect(...)) is not being handled—it simply does nothing. I understand that I could use useServerFn() to catch the redirect, but doing so would prevent me from using ensureQueryData. How can I properly handle the redirection thrown by getCurrentUserFn in the loader, while still using ensureQueryData (or an alternative)?
8 Replies
wise-white
wise-whiteOP5mo ago
Looks like it will redirect if I use useSuspenseQuery in the component but not when I use useQuery. Is there anyway to make it work with useQuery? bump
fascinating-indigo
fascinating-indigo5mo ago
are you in a hurry?
wise-white
wise-whiteOP5mo ago
I am sorry if I troubled you, but it will be helpful for me to know if I can do anything better here, or if there is any way to fix it. I hope it's fine to bump now.
fascinating-indigo
fascinating-indigo5mo ago
haha are you using react-router-with-query ? like in the query based start example
wise-white
wise-whiteOP5mo ago
Yeah, I am using "@tanstack/react-router-with-query" package and using it and router.tsx, and other steps as given in the examples It also redirects to the page when using throw redirect for half a second, but then returns to the original page. It works fine with useSuspenseQuery, but I prefer using useQuery since it allows me to pass isLoading to components further down the tree.
wise-white
wise-whiteOP5mo ago
I am not sure why but it's just showing blank page when using useSuspenseQuery now
fascinating-indigo
fascinating-indigo5mo ago
please create a complete minimal example repository and share that here
wise-white
wise-whiteOP5mo ago

Did you find this page helpful?