Replies: 2 comments
-
This would also be a great help for setting the <Form action="myRouteId"> |
Beta Was this translation helpful? Give feedback.
-
@kandros If you're just looking for ids and type safety, I've found the below pattern to work well. Name the types for your loaders (could work for actions too), define your route ids, and map your route ids to your types. Then you can use a couple wrapper functions for components and meta that will yell at you if you're passing an unknown route id and return the correct types based on the route. Note: I'm using the vite config to define my routes rather than file based routing, but there's no reason it wouldn't work with file based routing too. // ~/component/pages/SearchData.tsx
export async function loader() {
...
}
export type SearchLoader = typeof loader;
// ~/component/pages/SignUp.tsx
export async function loader() {
...
}
export type SignUpLoader = typeof loader;
// routeStuff.ts
import { MetaMatches } from "@remix-run/react/dist/routeModules";
import { SerializeFrom } from "@remix-run/node";
import { SearchLoader } from "~/components/pages/SearchData";
import { SignUpLoader } from "~/components/pages/SignUp";
import { useRouteLoaderData } from "react-router-dom";
export enum RouteIds {
SIGN_UP = "SignUp",
SEARCH = "SearchData",
}
interface RouteLoaders {
[RouteIds.SIGN_UP]: SignUpLoader;
[RouteIds.SEARCH]: SearchLoader;
}
export function metaRouteData<K extends keyof RouteLoaders>(
matches: MetaMatches,
routeId: K,
): SerializeFrom<RouteLoaders[K]> {
const match = matches.find(({ id }) => id === routeId);
if (!match) {
throw new Error(`Route loader data not found for "${routeId}"`);
}
return match.data as SerializeFrom<RouteLoaders[K]>;
}
export function useRouteData<K extends keyof RouteLoaders>(
routeId: K,
): SerializeFrom<RouteLoaders[K]> {
const data = useRouteLoaderData(routeId);
if (data === undefined) {
throw new Error(`Route loader data not found for "${routeId}"`);
}
return data as SerializeFrom<RouteLoaders[K]>;
}
// usage in some page
export const meta: MetaFunction = ({ matches, location }) => {
const searchData = metaRouteData(matches, RouteIds.SEARCH);
}
...
export default function MyPage() {
const searchData = useRouteData(RouteIds.SEARCH);
...
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
using utils like
useRouteLoaderData
anduseMatches
can be kind of cumbersome to write and maintain as moving files may result in hard to debug behaviouscurrent
proposed
PS: I would also prefer calling on a non-existing route to error instead of silently fail
Beta Was this translation helpful? Give feedback.
All reactions