TanStackT
TanStack10mo ago
2 replies
radical-lime

useLoaderData => Invariant failed

Hi,

I am trying get some data from a loader in layout component. That means the component might be rendered before that specific route with a loader is rendered which results in Invariant failed: Could not find an active match from .... This already points on where the issue is, but in my perspective this is a perfectly valid scenario, because if the route is not visited I expect the data to be undefined. As Tanstack Router is opinionated, my question is, what is the recommended approach for this particular case? I managed to work around this by combining useMatch with useLoaderData, but I don't like it as it feels dirty. So I'd like to know if there's a better approach, e.g. I am wondering why useLoaderData does not have shouldThrow option as useMatch does, because basically I can't handle the hook error in any way and as mentioned above I do expect the hook to fail in specific part of the route tree.

const wsMatch = useMatch({ from: "/workspace/$ws_id", shouldThrow: false });
const workspace = useLoaderData({
    from: wsMatch?.routeId ?? "__root__",
  })?.workspace;
Was this page helpful?