| 80 | * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchHook |
| 81 | */ |
| 82 | export function useMatch< |
| 83 | TRouter extends AnyRouter = RegisteredRouter, |
| 84 | const TFrom extends string | undefined = undefined, |
| 85 | TStrict extends boolean = true, |
| 86 | TThrow extends boolean = true, |
| 87 | TSelected = unknown, |
| 88 | TStructuralSharing extends boolean = boolean, |
| 89 | >( |
| 90 | opts: UseMatchOptions< |
| 91 | TRouter, |
| 92 | TFrom, |
| 93 | TStrict, |
| 94 | ThrowConstraint<TStrict, TThrow>, |
| 95 | TSelected, |
| 96 | TStructuralSharing |
| 97 | >, |
| 98 | ): ThrowOrOptional<UseMatchResult<TRouter, TFrom, TStrict, TSelected>, TThrow> { |
| 99 | const nearestMatchId = React.useContext( |
| 100 | opts.from ? dummyMatchContext : matchContext, |
| 101 | ) |
| 102 | |
| 103 | const matchSelection = useRouterState({ |
| 104 | select: (state: any) => { |
| 105 | const match = state.matches.find((d: any) => |
| 106 | opts.from ? opts.from === d.routeId : d.id === nearestMatchId, |
| 107 | ) |
| 108 | invariant( |
| 109 | !((opts.shouldThrow ?? true) && !match), |
| 110 | `Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`, |
| 111 | ) |
| 112 | |
| 113 | if (match === undefined) { |
| 114 | return undefined |
| 115 | } |
| 116 | |
| 117 | return opts.select ? opts.select(match) : match |
| 118 | }, |
| 119 | structuralSharing: opts.structuralSharing, |
| 120 | } as any) |
| 121 | |
| 122 | return matchSelection as any |
| 123 | } |