Open History to see the last commit
1import { useMatch } from './useMatch'
2import type {
3 StructuralSharingOption,
4 ValidateSelected,
5} from './structuralSharing'
6import type {
7 AnyRouter,
8 RegisteredRouter,
9 ResolveUseSearch,
10 StrictOrFrom,
11 ThrowConstraint,
12 ThrowOrOptional,
13 UseSearchResult,
14} from '@tanstack/router-core'
15β
16export interface UseSearchBaseOptions<
17 TRouter extends AnyRouter,
18 TFrom,
19 TStrict extends boolean,
20 TThrow extends boolean,
21 TSelected,
22 TStructuralSharing,
23> {
24 select?: (
25 state: ResolveUseSearch<TRouter, TFrom, TStrict>,
26 ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
27 shouldThrow?: TThrow
28}
29β
30export type UseSearchOptions<
31 TRouter extends AnyRouter,
32 TFrom,
33 TStrict extends boolean,
34 TThrow extends boolean,
35 TSelected,
36 TStructuralSharing,
37> = StrictOrFrom<TRouter, TFrom, TStrict> &
38 UseSearchBaseOptions<
39 TRouter,
40 TFrom,
41 TStrict,
42 TThrow,
43 TSelected,
44 TStructuralSharing
45 > &
46 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>
47β
48export type UseSearchRoute<out TFrom> = <
49 TRouter extends AnyRouter = RegisteredRouter,
50 TSelected = unknown,
51 TStructuralSharing extends boolean = boolean,
52 TThrow extends boolean = true,
53>(
54 opts?: UseSearchBaseOptions<
55 TRouter,
56 TFrom,
57 /* TStrict */ true,
58 TThrow,
59 TSelected,
60 TStructuralSharing
61 > &
62 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
63) => ThrowOrOptional<UseSearchResult<TRouter, TFrom, true, TSelected>, TThrow>
64β
65/**
66 * Read and select the current route's search parameters with type-safety.
67 *
68 * Options:
69 * - `from`/`strict`: Control which route's search is read and how strictly it's typed
70 * - `select`: Map the search object to a derived value for render optimization
71 * - `structuralSharing`: Enable structural sharing for stable references
72 * - `shouldThrow`: Throw when the route is not found (strict contexts)
73 *
74 * @returns The search object (or selected value) for the matched route.
75 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useSearchHook
76 */
77export function useSearch<
78 TRouter extends AnyRouter = RegisteredRouter,
79 const TFrom extends string | undefined = undefined,
80 TStrict extends boolean = true,
81 TThrow extends boolean = true,
82 TSelected = unknown,
83 TStructuralSharing extends boolean = boolean,
84>(
85 opts: UseSearchOptions<
86 TRouter,
87 TFrom,
88 TStrict,
89 ThrowConstraint<TStrict, TThrow>,
90 TSelected,
91 TStructuralSharing
92 >,
93): ThrowOrOptional<
94 UseSearchResult<TRouter, TFrom, TStrict, TSelected>,
95 TThrow
96> {
97 return useMatch({
98 from: opts.from!,
99 strict: opts.strict,
100 shouldThrow: opts.shouldThrow,
101 structuralSharing: opts.structuralSharing,
102 select: (match) => {
103 return opts.select ? opts.select(match.search) : match.search
104 },
105 }) as any
106}