Skip to content
Source
Sign inSign up
TanStack/router

useLoaderData with index route ("/") errors #5346

ClosedmGranTY(GitHub profile, opens in a new tab) opened this issue 4 comments

Which project does this relate to?

Router

Describe the bug

i'm using tanstack and have the following

probably related to _layout.$.tsx, maybe i didnt read something right?

my discord if anyone need any more info granty._.

...



export const Route = createFileRoute("/")({
    loader: async ({ location }) => {
        const search = new URLSearchParams(location?.search ?? "")
        const brandIdParam = search.get("brandId")
        const brandId = brandIdParam ? Number(brandIdParam) : undefined

        const [
            { data: departmentsRes },
            { data: bannersRes },
            { data: brandsRes },
            modelsRes,
            { data: highlightedRes },
            { data: businessRes },
        ] = await Promise.all([
            executeFromServerTyped(getAllDepartments, {}),
            executeFromServerTyped(getHomepageBanners, {}),
            executeFromServerTyped(getVehicleBrands, { isActive: true, limit: 100 }),
            brandId
                ? executeFromServerTyped(getVehicleModelsByBrand, { brandId, isActive: true })
                : Promise.resolve({ data: undefined as any }),
            executeFromServerTyped(getHighlightedCloudSearchProducts, { limit: 12 }),
            executeFromServerTyped(getBusinessInfo, {}),
        ]);

        const departments = departmentsRes?.departments ?? []
        const banners = bannersRes?.homepageBanners ?? []
        const brands = brandsRes?.vehicleBrands ?? []
        const models = modelsRes?.data?.vehicleModelsByBrand ?? []
        const business = businessRes?.businessInfo ?? null;
        const highlightedOffers: CloudSearchOffer[] =
            (highlightedRes?.highlightedCloudSearchProducts as CloudSearchOffer[]) ?? []

        return { departments, banners, brands, models, brandId, highlightedOffers, business };
    },
    component: RouteComponent,
})

function RouteComponent() {

    return (
        <>
            <Header />
        </>
    )
}

export default Route

where the Header component has this inside it:

export function Header() {
    const { departments, business } = useLoaderData({ from: "/" })

when header is rendered in the Index page it works just fine, however if it inside the _layout and replicated into other pages this happens:

invariant failed: could not find an active match from "/"

and crashes the app

the fix was to do: const { departments, business } = useLoaderData({ from: "" as "/" }) and it work for all routes now, not only

Your Example Website or App

https://stackblitz.com/edit/github-m2nhtzcu?file=src%2Froutes%2F__root.tsx

Steps to Reproduce the Bug or Issue

1 - go stackblitz page 2 - click at test anchor/link 3 - error should appear

Expected behavior

no invariant failed error

Screenshots or Videos

No response

Platform

  • Router / Start Version: "@tanstack/react-router": "1.132.31", "@tanstack/react-start": "1.132.31",

  • OS: Linux

  • Browser: Chrome

  • Browser Version: latest

  • Bundler: vite

  • Bundler Version: latest

Additional context

No response

  1. Suggestion, you can export the loader data in routes itself. Then pass the data using props into your child component. If you call the loaderData in child component, this will make you confuse and not consistent.

    // do this instead
    const {data} = Route.useLoaderData()
    
    // pass into child component
    ...
    <Header data={data}/>
  2. mGranTY(GitHub profile, opens in a new tab)commented

    Suggestion, you can export the loader data in routes itself. Then pass the data using props into your child component. If you call the loaderData in child component, this will make you confuse and not consistent.

    // do this instead const {data} = Route.useLoaderData()

    // pass into child component ...

    i was doing this but for the graphql i have, dealing with sharing via route is better for reusable layout components like header and footer.

  3. nyomansunima(GitHub profile, opens in a new tab)commented

    If you're sharing the the data for all of the routes in the same layout, better load it from the layout itself. Don't put your component in your file route.

    _layout.tsx --> put your header here not in your _layout.$.tsx file.

  4. you cannot access loader data from index if index is not rendered, which in case of /test path it is not, see the devtools

    Image

Sign in to join this conversation.