T
TanStack2w ago
vicious-gold

How can I throw redirect from inside a closure that was created inside a loader?

export const Route = createFileRoute('/_auth')({
loader: async ({ context: { queryClient, convexQueryClient } }) => {
const token = await getTokenApi()
if (token.length === 0) throw redirect({ to: '/login' })
if (convexQueryClient.serverHttpClient)
convexQueryClient.serverHttpClient.setAuth(token)
else
convexQueryClient.convexClient.setAuth(
() => Promise.resolve(token),
(isAuth) => {
if (!isAuth) throw redirect({ to: '/login' }) // problem.
}
)
await queryClient
.ensureQueryData(GetAccountsQuery())
.catch(() => logoutApi())
},
component: Component
})
export const Route = createFileRoute('/_auth')({
loader: async ({ context: { queryClient, convexQueryClient } }) => {
const token = await getTokenApi()
if (token.length === 0) throw redirect({ to: '/login' })
if (convexQueryClient.serverHttpClient)
convexQueryClient.serverHttpClient.setAuth(token)
else
convexQueryClient.convexClient.setAuth(
() => Promise.resolve(token),
(isAuth) => {
if (!isAuth) throw redirect({ to: '/login' }) // problem.
}
)
await queryClient
.ensureQueryData(GetAccountsQuery())
.catch(() => logoutApi())
},
component: Component
})
I think using a navigate function would be an appropriate solution, but it’s currently deprecated. If there’s a proper way to handle a redirect thrown from inside a closure created within a loader—without causing an uncaught promise error—I would appreciate any guidance.
/**
* @deprecated Use `throw redirect({ to: '/somewhere' })` instead
**/
navigate: (opts: NavigateOptions<AnyRouter>) => Promise<void> | void;
/**
* @deprecated Use `throw redirect({ to: '/somewhere' })` instead
**/
navigate: (opts: NavigateOptions<AnyRouter>) => Promise<void> | void;
No description
1 Reply
xenophobic-harlequin
xenophobic-harlequin2w ago
looks like you need to call router.navigate() in there?

Did you find this page helpful?