Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useLoaderData.tsx

91 lines2.4 KB

1import { useMatch } from './useMatch'
2import type {
3 StructuralSharingOption,
4 ValidateSelected,
5} from './structuralSharing'
6import type {
7 AnyRouter,
8 RegisteredRouter,
9 ResolveUseLoaderData,
10 StrictOrFrom,
11 UseLoaderDataResult,
12} from '@tanstack/router-core'
13​
14export interface UseLoaderDataBaseOptions<
15 TRouter extends AnyRouter,
16 TFrom,
17 TStrict extends boolean,
18 TSelected,
19 TStructuralSharing,
20> {
21 select?: (
22 match: ResolveUseLoaderData<TRouter, TFrom, TStrict>,
23 ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>
25​
26export type UseLoaderDataOptions<
27 TRouter extends AnyRouter,
28 TFrom extends string | undefined,
29 TStrict extends boolean,
30 TSelected,
31 TStructuralSharing,
32> = StrictOrFrom<TRouter, TFrom, TStrict> &
33 UseLoaderDataBaseOptions<
34 TRouter,
35 TFrom,
36 TStrict,
37 TSelected,
38 TStructuralSharing
39 > &
40 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>
41​
42export type UseLoaderDataRoute<out TId> = <
43 TRouter extends AnyRouter = RegisteredRouter,
44 TSelected = unknown,
45 TStructuralSharing extends boolean = boolean,
46>(
47 opts?: UseLoaderDataBaseOptions<
48 TRouter,
49 TId,
50 true,
51 TSelected,
52 TStructuralSharing
53 > &
54 StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,
55) => UseLoaderDataResult<TRouter, TId, true, TSelected>
56​
57/**
58 * Read and select the current route's loader data with type‑safety.
59 *
60 * Options:
61 * - `from`/`strict`: Choose which route's data to read and strictness
62 * - `select`: Map the loader data to a derived value
63 * - `structuralSharing`: Enable structural sharing for stable references
64 *
65 * @returns The loader data (or selected value) for the matched route.
66 * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLoaderDataHook
67 */
68export function useLoaderData<
69 TRouter extends AnyRouter = RegisteredRouter,
70 const TFrom extends string | undefined = undefined,
71 TStrict extends boolean = true,
72 TSelected = unknown,
73 TStructuralSharing extends boolean = boolean,
74>(
75 opts: UseLoaderDataOptions<
76 TRouter,
77 TFrom,
78 TStrict,
79 TSelected,
80 TStructuralSharing
81 >,
82): UseLoaderDataResult<TRouter, TFrom, TStrict, TSelected> {
83 return useMatch({
84 from: opts.from!,
85 strict: opts.strict,
86 structuralSharing: opts.structuralSharing,
87 select: (match) => {
88 return opts.select ? opts.select(match.loaderData) : match.loaderData
89 },
90 }) as UseLoaderDataResult<TRouter, TFrom, TStrict, TSelected>