Skip to content

Instantly share code, notes, and snippets.

@andrelandgraf
Last active November 19, 2022 06:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andrelandgraf/361f09ab0d4545463f91348d241ff364 to your computer and use it in GitHub Desktop.
Save andrelandgraf/361f09ab0d4545463f91348d241ff364 to your computer and use it in GitHub Desktop.
Wrapper hook for useMatches to quickly access loader data across components in Remix.run
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;
}
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 };
}
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