Skip to content
Source
Sign inSign up
TanStack/router

getRouteApi().useRouteContext() returns undefined for beforeLoad context values in v1.140.1+ #6082

Closedamanmavai(GitHub profile, opens in a new tab) opened this issue 16 comments

Which project does this relate to?

Router

Describe the bug

This is the bun monorepo : https://github.com/amanmavai/mn_projects, I am working on which has one backend bun_api_space and one frontend project tanstack_router_space It has auth setup using better-auth

The app was working fine till version 1.40.0 , below commands can verify

  1. start the backend bun --filter bun_api_space dev
  2. run the e2e testcases, cd to tanstack_router_space project, then run bun run test:e2e

After I have upgraded to 1.40.1, the e2e test command started failing Also when I run the app in dev mode, its not working, it seems authClient is not defined

Your Example Website or App

https://github.com/amanmavai/mn_projects

Steps to Reproduce the Bug or Issue

  1. change all the @tanstack packages in root of monorepo in the catalog section to version 1.40.1
  2. run bun install
  3. start the backend bun --filter bun_api_space dev
  4. run the e2e testcases, cd to tanstack_router_space project, then run bun run test:e2e
  5. or run the dev server and check if the app is not running

Expected behavior

Ideally the app should run fine as it was running on or before version 1.40.0

Screenshots or Videos

No response

Platform

  • Router / Start Version: [e.g. 1.40.1]
  • OS: macOS
  • Browser: Chrome

Additional context

No response

  1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

    📝 CodeRabbit Plan Mode

    Generate an implementation plan and prompts that you can use with your favorite coding agent.

    • Create Plan
    Examples
    You can configure auto-planning by selecting labels in the issue_enrichment configuration.

    TanStack/router#5406 - fix(router-devtools-core): bundle solid for smaller package [merged] TanStack/router#5422 - fix(router-devtools-core): actually bundle solid [merged] TanStack/router#5474 - chore: bump @tanstack/config to v0.22.0 [merged] TanStack/router#5680 - fix(router): bump tanstack store to ^0.8 [merged]

    👤 Suggested Assignees


    🧪 Issue enrichment is currently in early access.

    To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

    issue_enrichment:
      auto_enrich:
        enabled: false
  2. amanmavai(GitHub profile, opens in a new tab) changed the title

  3. schiller-manuel(GitHub profile, opens in a new tab)commented

    please try latest version, and if that doesn't work either, please provide error messages.

  4. schiller-manuel(GitHub profile, opens in a new tab) added labelsinformation needed

  5. Yes, I have tried with latest version as well, getting the same issue.

    I get the following error when I am running in dev mode

    TypeError: Cannot read properties of undefined (reading 'useSession')
        at SignedOut (auth-components.tsx:22:49)
        at Object.react_stack_bottom_frame (react-dom_client.js?v=cc2383de:18509:20)
        at renderWithHooks (react-dom_client.js?v=cc2383de:5654:24)
        at updateFunctionComponent (react-dom_client.js?v=cc2383de:7475:21)
        at beginWork (react-dom_client.js?v=cc2383de:8525:20)
        at runWithFiberInDEV (react-dom_client.js?v=cc2383de:997:72)
        at performUnitOfWork (react-dom_client.js?v=cc2383de:12561:98)
        at workLoopSync (react-dom_client.js?v=cc2383de:12424:43)
        at renderRootSync (react-dom_client.js?v=cc2383de:12408:13)
        at performWorkOnRoot (react-dom_client.js?v=cc2383de:11827:37)

    actually on or before 1.40.0 version, Signout component was not being executed I believe, only after the beforeLoad of __root executes completely then other components start executing. it seems that has changed somehow now.

  6. would be great if you could strip down the reproducer to the bare minimum

  7. amanmavai(GitHub profile, opens in a new tab)commented

    I have created another tanstack router repo which is CSR app, with this app, we are able to reproduce the issue without the backend. https://github.com/amanmavai/tanstack_router_open/tree/main

    use following commands

    1. bun install
    2. bun run dev
    3. you will see the error

    after you update the version back to 1.40.0, the error goes away.

    Kindly see below images with console logs, there is a difference in the sequence of logs:

    version 1.40.0

    Image

    version 1.40.1

    Image

    in the above images, we see after we upgrade to the faulty version, the logs changes a bit towards the end.

    during my debugging, in the new falty version, the authClient is defined during the beforeLoad execution after authClient is awaited. but its not available in SignedOut component when we access it using useAuthClient() hook

  8. It seems this might be because of the way I access root route context in this code

    // common.hooks.ts
    import {getRouteApi, rootRouteId} from "@tanstack/react-router";
    
    const routeApi = getRouteApi(rootRouteId);
    
    export const useAuthClient = () => {
      const {authClient} = routeApi.useRouteContext();
      return authClient;
    };
    

    is this way not supported anymore? esp on or after 1.40.1. if so what is the correct way to access root route context in a common hook

  9. amanmavai(GitHub profile, opens in a new tab)commented

    I tried to dig through the router code using cursor, and found this info below, hope this would be useful for you guys

    Title: getRouteApi().useRouteContext() returns undefined for beforeLoad context values in v1.140.1+
    
    The change in PR #6053 ("commit route context") defers context updates until after the loader completes.
    
    For routes without a loader, useRouteContext() returns undefined for values returned from beforeLoad.
    
    Regression in: v1.140.1
    Working in: v1.140.0
    
    Root cause: packages/router-core/src/load-matches.ts now only calls commitContext() 
    after the loader, but useRouteContext() reads match.context which is not updated 
    after beforeLoad alone.
  10. amanmavai(GitHub profile, opens in a new tab) changed the title

  11. @schiller-manuel could you check this now, I have provided the relevant information as requested

  12. Also ran into this issue - I hope it's not an intentional change. @amanmavai can you explain how exactly adding a loader should avoid the issue? Would that be a loader on the route that is adding to context, or in the child route that consumes that context?

  13. @dylanhu7 no this not an intentional change, it's a bug

  14. schiller-manuel(GitHub profile, opens in a new tab) removed labelsinformation needed

  15. @schiller-manuel , any update on this issue, This is a blocker for my usecase, I have not been able to upgrade my app since this issue

  16. TommysG(GitHub profile, opens in a new tab)commented

    Same problem here. I have this in my file route:

    export const Route = createFileRoute('/_app/(profile)/profile/')({
      beforeLoad: () => {
        return {
          myProfileQuery: fetchMyProfileQuery,
        };
      },
      loader: async ({ context }) => {
        await context.queryClient.ensureQueryData(context.myProfileQuery);
        return;
      },
      component: RouteComponent,
    });

    and when using it like this inside my RouteComponent i get this locally Cannot read properties of undefined (reading 'queryFn'). After refreshing it's ok, until i hard refresh and go to this route again. Happens only locally for me, in production is working.

      const { myProfileQuery } = Route.useRouteContext();
    
      const { data: profile } = useSuspenseQuery(myProfileQuery);
  17. I actually am seeing this issue in production. It's rare, but I got a sentry alert from it yesterday. So I don't think it's a dev-only issue, though it is much more common in dev.

  18. TommysG(GitHub profile, opens in a new tab)commented

    I actually am seeing this issue in production. It's rare, but I got a sentry alert from it yesterday. So I don't think it's a dev-only issue, though it is much more common in dev.

    I cannot understand why and when it triggers or if there is a workaround to fix it. I keep trying to reproduce it on production but no way… in dev it's constantly happening.

  19. Hi @schiller-manuel

    For my case, the issue appeared exactly after 1.140.1 and it's not fixed after #6407 (1.151.2) 🥹 Could you take a look at the issue if something else is wrong?

    For my case, my router looks like this

    • pathless layout + beforeLoad
      • page A + loader
    • page B

    When I navigate from page A to page B, the beforeLoad from layout context is initlally empty.

    layout beforeLoad start
    layout beforeLoad end
    page A loader start
    page A render beforeLoad: false loader: true
    page A render beforeLoad: false loader: true
    page A loader end
    page A render beforeLoad: true loader: true
    page A render beforeLoad: true loader: true

    here is the log, the beforeLoad is fired but it is not injected to useRouteContext call inside page A. Then after the page loader invalidates it rerenders the page - and the beforeLoad is correctly filled.

    I am willing to create a reproduction but the behavior is very inconsistent :(

  20. @ha1fstack please open a new issue including a complete reproducer project

Sign in to join this conversation.