T
TanStack6mo ago
absent-sapphire

Flash of incorrect route before navigation

I'm experiencing an issue where I'm seeing the wrong route before being navigated to the correct route via router.navigate(). I'm positive it's due to me not yet having a complete mental model of how Tanstack Start/Router works, so any help would be very appreciated. In my app, when users navigate to /onboarding, I want to first see if there is an eligible existing organization for them to join. If there is, they should be redirected to /onboarding/join. If there isn't, they can create a new organization at the /onboarding index route. Here's the logic in the /onboarding layout route (routes/onboarding/route.tsx):
export const Route = createFileRoute('/onboarding')({
beforeLoad: async ({ context }) => {
/// Verify user is logged in
},
loader: async ({ context: { queryClient } }) => {
await queryClient.ensureQueryData(orgQueries.joinable())
},
component: RouteComponent,
})

function RouteComponent() {
const router = useRouter()

const { data: org } = useSuspenseQuery(orgQueries.joinable())

if (org) {
router.navigate({ to: '/onboarding/join' })
}

return <Outlet />
}
export const Route = createFileRoute('/onboarding')({
beforeLoad: async ({ context }) => {
/// Verify user is logged in
},
loader: async ({ context: { queryClient } }) => {
await queryClient.ensureQueryData(orgQueries.joinable())
},
component: RouteComponent,
})

function RouteComponent() {
const router = useRouter()

const { data: org } = useSuspenseQuery(orgQueries.joinable())

if (org) {
router.navigate({ to: '/onboarding/join' })
}

return <Outlet />
}
However, when we visit /onboarding and there is a joinable organization, I see the index route for a split second before being redirected. Any guidance as to conceptually why this is happening would be so helpful. I'm not even sure if the layout route component is the best place to handle the logic to check if a joinable organization exists, and redirect if not. Thank you!
2 Replies
correct-apricot
correct-apricot6mo ago
you should throw a redirect instead of navigating in the component. either from beforeload or from the loader
absent-sapphire
absent-sapphireOP6mo ago
Got it, thanks Manuel!

Did you find this page helpful?