TanStackT
TanStack3mo ago
1 reply
radical-lime

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
})


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;
image.png
Was this page helpful?