Documentation

Relay preload example

Prepare a Relay query from route variables and router context.

When the router context carries a Relay environment, route prepare functions can preload queries before the page renders.

import { loadQuery, type PreloadedQuery } from 'react-relay';
import { type Environment } from 'relay-runtime';
import { type RoutePrepare } from '@plumile/router';

import {
  ProjectPageQuery,
  type ProjectPageQueryType,
} from '../queries/ProjectPageQuery.js';

export type AppRouterContext = {
  relayEnvironment: Environment;
};

export type ProjectPagePrepared = {
  query: PreloadedQuery<ProjectPageQueryType>;
  organizationSlug: string;
  projectSlug: string;
};

export const prepareProjectPage: RoutePrepare<
  AppRouterContext,
  ProjectPagePrepared,
  { organizationSlug: string; projectSlug: string }
> = ({ context, variables }) => {
  const query = loadQuery<ProjectPageQueryType>(
    context.relayEnvironment,
    ProjectPageQuery,
    {
      organizationSlug: variables.organizationSlug,
      projectSlug: variables.projectSlug,
    },
  );

  return {
    query,
    organizationSlug: variables.organizationSlug,
    projectSlug: variables.projectSlug,
  };
};

Return the query reference and any route variables the page needs. Keep Relay environment creation outside the route module and pass it through router context.

For backoffice Relay configuration, see Backoffice Relay.