UNPKG

@tanstack/react-router

Version:

Modern and scalable routing for React applications

50 lines (49 loc) 2.04 kB
import { dummyMatchContext, matchContext } from "./matchContext.js"; import { useRouter } from "./useRouter.js"; import { invariant, replaceEqualDeep } from "@tanstack/router-core"; import * as React$1 from "react"; import { useStore } from "@tanstack/react-store"; import { isServer } from "@tanstack/router-core/isServer"; //#region src/useMatch.tsx var dummyStore = { state: void 0, get: () => void 0, subscribe: () => () => {} }; /** * Read and select the nearest or targeted route match. * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchHook */ function useMatch(opts) { const router = useRouter(); const nearestMatchId = React$1.useContext(opts.from ? dummyMatchContext : matchContext); const key = opts.from ?? nearestMatchId; const matchStore = key ? opts.from ? router.stores.getMatchStoreByRouteId(key) : router.stores.activeMatchStoresById.get(key) : void 0; if (isServer ?? router.isServer) { const match = matchStore?.state; if ((opts.shouldThrow ?? true) && !match) { 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(); } if (match === void 0) return; return opts.select ? opts.select(match) : match; } const previousResult = React$1.useRef(void 0); return useStore(matchStore ?? dummyStore, (match) => { if ((opts.shouldThrow ?? true) && !match) { 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(); } if (match === void 0) return; const selected = opts.select ? opts.select(match) : match; if (opts.structuralSharing ?? router.options.defaultStructuralSharing) { const shared = replaceEqualDeep(previousResult.current, selected); previousResult.current = shared; return shared; } return selected; }); } //#endregion export { useMatch }; //# sourceMappingURL=useMatch.js.map