-
-
Save AnthoniG/5fd9260c2d79977106ab1fe659b6e501 to your computer and use it in GitHub Desktop.
Wrapper hook for useMatches to quickly access loader data across components in Remix.run
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMatches } from 'remix'; | |
// this base hook is used in other hooks to quickly search for specific data across all loaderData using useMatches | |
// see in action: https://codesandbox.io/s/usematches-loader-data-2h798?file=/app/db.server.ts | |
export default function useLoaderStore<T>(key: string): T | undefined { | |
const matchingRoutes = useMatches(); | |
const route = matchingRoutes.find((route) => route.data && route.data[key]); | |
if (!route || !route.data || route.data[key] === undefined) { | |
return undefined; | |
} | |
return route.data[key] as T; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { PopulatedProject } from '~/types'; | |
import useLoaderStore from './useLoaderStore'; | |
// does not use invariant => project can be undefined | |
export default function useProject() { | |
const project = useLoaderStore<PopulatedProject>('project'); | |
return { project }; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { PopulatedProject } from '~/types'; | |
import invariant from 'tiny-invariant'; | |
import useLoaderStore from './useLoaderStore'; | |
// uses invariant => projects is always defined, will throw runtime error otherwise | |
export default function useProjects() { | |
const projects = useLoaderStore<PopulatedProject[]>('projects'); | |
invariant(projects, 'projects must be defined'); | |
return { projects }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment