router icon indicating copy to clipboard operation
router copied to clipboard

Error after upgrading to v1.121.0 - `Invariant failed: Could not find a nearest match!`

Open josippapez opened this issue 7 months ago • 4 comments

Which project does this relate to?

Start

Describe the bug

After upgrading all the packages and going through the migration guide, when I try to start up the app I get this error:

[vite] connected.
Error in renderToPipeableStream: Error: Invariant failed: Could not find a nearest match!
    at invariant (file:///Users/josippapez/Desktop/brisk-fit-web-static/node_modules/tiny-invariant/dist/esm/tiny-invariant.js:12:11)
    at Object.select (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/@tanstack/react-router/src/useMatch.tsx:104:7)
    at <anonymous> (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/@tanstack/react-router/src/useRouterState.tsx:55:19)
    at memoizedSelector (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:47:30)
    at /Users/josippapez/Desktop/brisk-fit-web-static/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:76:26
    at Object.useSyncExternalStore (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/react-dom/cjs/react-dom-server.node.development.js:9126:18)
    at process.env.NODE_ENV.exports.useSyncExternalStore (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/react/cjs/react.development.js:1228:34)
    at process.env.NODE_ENV.exports.useSyncExternalStoreWithSelector (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js:82:19)
    at useStore (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/@tanstack/react-store/src/index.ts:23:17)
    at useRouterState (/Users/josippapez/Desktop/brisk-fit-web-static/node_modules/@tanstack/react-router/src/useRouterState.tsx:45:10) { componentStack: [Getter] }

Your Example Website or App

none

Steps to Reproduce the Bug or Issue

  1. Upgrade to v1.121.0
  2. Go through the migration guide
  3. Try to start the app

Expected behavior

It should start as it did before the migration

Screenshots or Videos

No response

Platform

  • OS: macOS
  • Browser: Firefox (Zen Browser)
  • Version: latest zen browser

Additional context

No response

josippapez avatar Jun 11 '25 10:06 josippapez

This is @tanstack/react-start-client. See my comment here https://github.com/TanStack/router/issues/4380#issuecomment-2963391902

wobsoriano avatar Jun 11 '25 17:06 wobsoriano

This is @tanstack/react-start-client. See my comment here #4380 (comment)

I'm not really sure how your comment about pinning the version of packages helps. I'm just following the migration guide listed under the release version and this is the error after it. Also, i'm not getting the error in the issue you mentioned + i'm not using clerk

josippapez avatar Jun 11 '25 18:06 josippapez

This is @tanstack/react-start-client. See my comment here #4380 (comment)

I'm not really sure how your comment about pinning the version of packages helps. I'm just following the migration guide listed under the release version and this is the error after it. Also, i'm not getting the error in the issue you mentioned + i'm not using clerk

Ah, apologies. On my end Im getting the same error in my existing TanStack app without pinning the same version of @tanstack/react-start-client with the other tanstack deps.

Have you tried deleting node_modules and your lockfile and reinstalling?

wobsoriano avatar Jun 11 '25 18:06 wobsoriano

Yep, that was my first though when i saw this. Unfortunately, it did nothing

josippapez avatar Jun 12 '25 05:06 josippapez

same error, trying to upgrade from v1.117 to 1.127.3.

After further investigation it is related to a context that I added to Router's InnerWrap because the context needs useNavigate hook.

The fix is to remove it from createRouter / InnerWrap and add it to my root Route.

Instead of

const router = createRouter({
  routeTree,
  InnerWrap: ({ children }) => {
     return (<ProblemContext>{children}</ProblemContext>)
  }

I'm moving it to:

export const Route = createRootRoute({
  component: () => (
    <ProblemContext>
      <RootLayout />
    </ProblemContext>
  ),
})

my163cih avatar Jul 14 '25 02:07 my163cih

@my163cih I'll definitely try this one out later but still, it seems like a bug to me

josippapez avatar Jul 14 '25 11:07 josippapez

Having the same issue here. I'd like to know what exactly this error is supposed to mean... if it can't find a route / match, why isn't throwing a not found error?

More information: When I load the app, it works (on any route, it displays what it should). When I click a link, any link, it breaks with the error "can't find a nearest match". What's funny is that if I then reload the page, the route load properly.

Also, I'd like to share how painful this library is to update. I'm at the point where I regret not going with react-router. It's very hard to keep up with all updates, AND there are breaking changes almost every time.

Mboulianne avatar Jul 15 '25 11:07 Mboulianne

@my163cih Thanks for the suggestion! I tried it out now and it fixed my issue and the app works fine for me now. Don't know what caused the bug but it still stands

josippapez avatar Jul 15 '25 13:07 josippapez

@Mboulianne

Start is still in beta, so breaking changes can and will occur until we declare the API to be stable. we track all the breaking change here. I don't see "breaking changes almost every time."

schiller-manuel avatar Jul 15 '25 20:07 schiller-manuel

@josippapez do we have a complete reproducer project for this error?

schiller-manuel avatar Jul 15 '25 20:07 schiller-manuel

@schiller-manuel not for now unfortunately. I can try reproducing it by the end of the week but in my case, project started working after moving a provider that contains useRouterState hook to the root instead of using it in the innerWrapper in createRouter

josippapez avatar Jul 15 '25 20:07 josippapez

can you roughly sketch out the code of the wrapper etc?

schiller-manuel avatar Jul 15 '25 20:07 schiller-manuel

@schiller-manuel sure. I'll copy the code here.


import { getDefaultOptions, setDefaultOptions } from 'date-fns';
import { I18nextProvider } from 'react-i18next';
import { useAtomValue } from 'jotai';
import { NuqsAdapter } from 'nuqs/adapters/react';
import { useNavigate, useRouter } from '@tanstack/react-router';
import { default as i18next } from '@modules/shared/localization/i18n';
import { MappedLocales } from '@modules/shared/localization/const/language';
import { Days } from '@modules/shared/utils';
import { settingsAtom } from '@state/atoms';
import type { Day } from 'date-fns';
import type { PropsWithChildren } from 'react';

export const Providers: React.FC<PropsWithChildren> = ({ children }) => {
  const navigate = useNavigate();
  const { state } = useRouter();
  const profileSettings = useAtomValue(settingsAtom);
  const matchedLocation = state.matches.at(-1);

  if (!getDefaultOptions().locale) {
    // needed for initial render to be in the correct language
    i18next.emit('initialized');
  }

  i18next.on('initialized', () => {
    setDefaultOptions({
      locale: MappedLocales.get(i18next.language),
      weekStartsOn: profileSettings.startDayOfWeek
        ? (Days[profileSettings.startDayOfWeek as keyof typeof Days] as Day)
        : undefined,
    });
  });

  i18next.on('languageChanged', async (lng: string) => {
    const defaultOptions = getDefaultOptions();

    if (
      defaultOptions.locale?.code !== lng ||
      defaultOptions.weekStartsOn !==
        Days[profileSettings.startDayOfWeek as keyof typeof Days]
    ) {
      setDefaultOptions({
        locale: MappedLocales.get(lng),
        weekStartsOn: profileSettings.startDayOfWeek
          ? (Days[profileSettings.startDayOfWeek as keyof typeof Days] as Day)
          : undefined,
      });
    }

    await navigate({
      to: matchedLocation?.fullPath || '/$locale',
      // @ts-ignore-next-line
      params: { locale: lng },
    });
  });

  return (
    <I18nextProvider i18n={i18next} defaultNS={'translation'}>
      <NuqsAdapter>{children}</NuqsAdapter>
    </I18nextProvider>
  );
};

josippapez avatar Jul 15 '25 20:07 josippapez

@schiller-manuel, I have a fairly minimum reproducible example. This was forked from a working min file-based router example: CodeSandbox

In the example, I have a context (MyContext) that basically does nothing except for requiring useNavigate hook. This is to simulate situation where we need to navigate to certain routes within the context.

The context is added as child to Router via InnerWrap:

  InnerWrap: ({children}) => (
    <MyContextProvider>{children}</MyContextProvider>
  )

But, when useNavigate is called const navigate = useNavigate(), the error occurs:

 Uncaught Error: Invariant failed: Could not find a nearest match!
    at invariant (chunk-RYSA4V6F.js?v=cbdeabb4:13:9)
    at Object.select (chunk-VGRA4EUZ.js?v=cbdeabb4:481:7)
    at chunk-VGRA4EUZ.js?v=cbdeabb4:458:19
    at memoizedSelector (chunk-VGRA4EUZ.js?v=cbdeabb4:144:32)
    at chunk-VGRA4EUZ.js?v=cbdeabb4:164:24
    at mountSyncExternalStore (react-dom_client.js?v=6cc93410:4550:26)
    at Object.useSyncExternalStore (react-dom_client.js?v=6cc93410:16562:18)
    at exports.useSyncExternalStore (chunk-2HR2RAAS.js?v=cbdeabb4:930:36)
    at exports.useSyncExternalStoreWithSelector (chunk-VGRA4EUZ.js?v=cbdeabb4:173:21)
    at useStore (chunk-VGRA4EUZ.js?v=cbdeabb4:369:75)

if I comment out the line calling useNavigate, the error is gone.

my163cih avatar Jul 15 '25 21:07 my163cih

@Mboulianne

Start is still in beta, so breaking changes can and will occur until we declare the API to be stable. we track all the breaking change here. I don't see "breaking changes almost every time."

The problem is I'm not using start, and changes introduced for start has been nothing but trouble for me. You communicated a lot about the devinxi migration, but you forgot people who are not using start.

2-3 weeks ago I had to go through this https://github.com/TanStack/router/issues/4380#issuecomment-3012836414 where I needed to add a dependency to my project otherwise it'd break my routing when updating my lock file. You even answered that specific comment, so I'll let you go back and read it :).

and now this.

Anyway I'm done. I just went back to react-router, even though it pains me. tanstack/router just wasn't mature enough for our team.

Mboulianne avatar Jul 17 '25 12:07 Mboulianne