Skip to content

[WIP] How to better structure Route <-> Router to avoid circular references #510

Description

@Newbie012

Describe the bug

Given the following setup:

// src/routes/a.tsx

import { Route } from "@tanstack/react-router";
import { rootRoute } from "./_root";
import { router } from "./_router";

export const aRoute = new Route({
    getParentRoute: () => rootRoute,
    component: () => <></>
    path: "a",
    beforeLoad: () => {
        console.log(router.basepath); // <--- note this line
    }
});
// src/routes/_router.tsx

import { ReactRouter } from "@tanstack/react-router";
import { aRoute } from "./a";
import { rootRoute } from "./_root";

export const routeTree = rootRoute.addChildren([aRoute]);
export const router = new ReactRouter({ routeTree });
// src/routes/_root.tsx

import { RootRoute } from "@tanstack/react-router";

export const rootRoute = RootRoute.withRouterContext()();

Each time I save the file a.tsx, I get the following error (due to an attempt of HMR):

image

This makes sense since they all reference each other in a circular way. In order to fix that, I need to use the router that I get inside beforeLoad instead. But the problem is that it's AnyRouter which isn't type-safe.

Your Example Website or App

https://github.com/Newbie012/tanstack-router-circular-reference

Steps to Reproduce the Bug or Issue

  1. Clone https://github.com/Newbie012/tanstack-router-circular-reference
  2. Run pnpm install
  3. Run pnpm dev
  4. Open browser, and navigate to http://localhost:5173/a
  5. Attempt to modify the file src/routes/a.tsx
  6. See an error (image above) in the console:
ReferenceError: Cannot access 'aRoute' before initialization
    at _router.tsx:5:49
[hmr] Failed to reload /src/routes/a.tsx. This could be due to syntax errors or importing non-existent modules. (see errors above)

Expected behavior

Should not throw that error

Screenshots or Videos

image

Platform

  • OS: Windows (WSL2 Ubuntu)
  • Browser: Chrome
  • Version: Version 109.0.5414.120 (Official Build) (64-bit)

Additional context

Really cool library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions