T
TanStack6mo ago
national-gold

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;
const wsMatch = useMatch({ from: "/workspace/$ws_id", shouldThrow: false });
const workspace = useLoaderData({
from: wsMatch?.routeId ?? "__root__",
})?.workspace;
2 Replies
wise-white
wise-white6mo ago
sure we could addThrow to useLoaderData. we have open PRs for other hooks for the same option , please have a look
national-gold
national-goldOP6mo ago
lovely, thanks Manuel!

Did you find this page helpful?