@tanstack/solid-router
Version:
Modern and scalable routing for Solid applications
35 lines • 1.79 kB
JSX
import * as Solid from 'solid-js';
import invariant from 'tiny-invariant';
import { useRouterState } from './useRouterState';
import { dummyMatchContext, matchContext } from './matchContext';
export function useMatch(opts) {
const nearestMatchId = Solid.useContext(opts.from ? dummyMatchContext : matchContext);
// Create a signal to track error state separately from the match
const matchState = useRouterState({
select: (state) => {
const match = state.matches.find((d) => opts.from ? opts.from === d.routeId : d.id === nearestMatchId());
if (match === undefined) {
// During navigation transitions, check if the match exists in pendingMatches
const pendingMatch = state.pendingMatches?.find((d) => opts.from ? opts.from === d.routeId : d.id === nearestMatchId());
// Determine if we should throw an error
const shouldThrowError = !pendingMatch && !state.isTransitioning && (opts.shouldThrow ?? true);
return { match: undefined, shouldThrowError };
}
return {
match: opts.select ? opts.select(match) : match,
shouldThrowError: false,
};
},
});
// Use createEffect to throw errors outside the reactive selector context
// This allows error boundaries to properly catch the errors
Solid.createEffect(() => {
const state = matchState();
if (state.shouldThrowError) {
invariant(false, `Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`);
}
});
// Return an accessor that extracts just the match value
return Solid.createMemo(() => matchState().match);
}
//# sourceMappingURL=useMatch.jsx.map