How to get an array of all possible route names for useRoute
.
#28
-
In my export const router = createRouter({
Root: "/",
Index: "/contacts",
Contact: "/contacts/:id",
EditContact: "/contacts/:id/edit",
DestroyContact: "/contacts/:id/destroy",
});
// remove pushRoute, push and replace
export const allRouteNames = Object.keys(router).filter(
/^[A-Z].*/.test
) as Parameters<typeof router.useRoute>[0];
const App: FC = async () => {
const route = router.useRoute(allRouteNames)!;
switch (route.name) {
case "Root":
return <Root />;
case "Contact":
return <Contact contactId={route.params.id} />;
case "EditContact":
return <EditContact contactId={route.params.id} />;
case "DestroyContact":
await deleteContact(route.params.id);
return router.push("Root");
default:
route satisfies never;
}
}; |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I think this is the same problem as #27 |
Beta Was this translation helpful? Give feedback.
-
@1EDExg0ffyXfTEqdIUAYNZGnCeajIxMWd2vaQeP #27 is not the same issue. But #3 is, yeah. const routes = {
Root: "/",
Index: "/contacts",
Contact: "/contacts/:id",
EditContact: "/contacts/:id/edit",
DestroyContact: "/contacts/:id/destroy",
} as const; // declare routes as const
type Routes = typeof routes;
type RouteName = keyof Routes;
export const router = createRouter(routes);
// the cast is necessary since Object.keys typing is not that good
// https://swan-io.github.io/boxed/dict doesn't have this issue
export const routeNames = Object.keys(routes) as RouteName[];
// You can also consider:
export const useAllRoutes = () => useRoute(routeNames);
const App: FC = async () => {
const route = router.useRoute(routeNames);
switch (route.name) {
case "Root":
return <Root />;
case "Contact":
return <Contact contactId={route.params.id} />;
case "EditContact":
return <EditContact contactId={route.params.id} />;
case "DestroyContact":
await deleteContact(route.params.id);
return router.push("Root");
default:
// route satisfies never;
}
}; |
Beta Was this translation helpful? Give feedback.
@1EDExg0ffyXfTEqdIUAYNZGnCeajIxMWd2vaQeP #27 is not the same issue. But #3 is, yeah.
This can be easily solved using idiomatic TypeScript: