UNPKG

@tanstack/solid-router

Version:

Modern and scalable routing for Solid applications

50 lines • 1.91 kB
import * as Solid from 'solid-js'; import { invariant, replaceEqualDeep } from '@tanstack/router-core'; import { nearestMatchContext } from './matchContext'; import { useRouter } from './useRouter'; export function useMatch(opts) { const router = useRouter(); const contextMatch = Solid.useContext(nearestMatchContext); const nearestMatch = opts.from ? undefined : contextMatch; const match = () => { if (opts.from) { return router.stores.getMatchStore(opts.from).get(); } return nearestMatch?.[1 /* match */](); }; // The returned accessor can be read after the owning scope has been // disposed (e.g. async work started by a route component that resolves // after navigating away). Once disposed, keep returning the last known // value instead of dropping to undefined for the now-missing match. let isDisposed = false; if (Solid.getOwner()) { Solid.onCleanup(() => { isDisposed = true; }); } Solid.createEffect(match, (selectedMatch) => { if (selectedMatch !== undefined) { return; } if (opts.shouldThrow ?? true) { if (process.env.NODE_ENV !== 'production') { throw new Error(`Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`); } invariant(); } }); return Solid.createMemo((prev) => { const selectedMatch = match(); if (selectedMatch === undefined) { if (prev !== undefined && isDisposed) { return prev; } return undefined; } const res = opts.select ? opts.select(selectedMatch) : selectedMatch; if (prev === undefined) return res; return replaceEqualDeep(prev, res); }); } //# sourceMappingURL=useMatch.jsx.map