Typing definition for loader and action hooks #11411
Replies: 1 comment 3 replies
-
Remix as of v2.9 with The current hook, To workaround this issue, you can create a simple wrapper function: export function useTypedLoaderData<T extends LoaderFunction>() {
return useLoaderData() as Awaited<ReturnType<T>>;
} export function loader() {
return { message: 'hello, world', now: new Date() }
}
export default function Component() {
const data = useTypedLoaderData<typeof loader>()
//^? const data: { message: string; now: Date; }
console.log(data.now.toLocaleDateString())
} All this to say is that now that Remix supports returning naked objects with the correct native types, this means that Remix and React Router will have feature parity, since a React Router Anyway, I think this is what they mean by waiting for Remix v3. From the looks of things, it seems that React Router v7 may pretty much merge in Remix directly as a single library (instead of separate Remix v3) that can span from SPA to SSR and everything in between. |
Beta Was this translation helpful? Give feedback.
-
Summary
Currently, hooks related to data fetching and mutation like
useLoaderData
anduseActionData
does not provide any possibility to proper define the typing of their return values.This subject was already discussed multiple times with proposed solutions (see references below) since 2022 but nothing out as far as I'm writing this thread.
So I would like to start a new discussion to get a status it.
Closed proposition
A Pull Request was already proposed to implement such a thing (#9670) but was closed with the argument of waiting about typing reconsideration with Remix v3: #9670 (comment)
However, I don't see any development trace neither road-map about this version 3 of Remix neither any discussion about the related typing subject. May you give us some links?
Similar already existing implementations
Similar implementations for type inference already exists on some of the proposed hooks:
react-router/packages/react-router/lib/hooks.tsx
Lines 293 to 295 in 241f2d4
react-router/packages/react-router/lib/hooks.tsx
Lines 131 to 134 in 241f2d4
Why not proposing something equivalent?
Existing solution trough external library
@fredericoo created a library to provide type safety with the mentioned hook: https://github.com/fredericoo/react-router-typesafe
This manner looks to be quite reliable. Is considering the implementation of such a solution under your official namespace a possibility? If not, why?
Many thanks.
References
useActionData
&useLoaderData
hooks #9670json
&redirect
functions #9669Beta Was this translation helpful? Give feedback.
All reactions