reactjsreact-router

React Router 7 accessing loaderData in meta function


I tried reading the React Router 7 documentation, but can't seem to find a solution to my issue.

So in my React Router 7 Node.js/Express app, I have a loader function for the client, to fetch location data before the app renders:

import type { Route } from "./+types/main-layout-route";

export async function clientLoader({}: Route.ClientLoaderArgs) {
  try {
    const response = await fetch(`https://geolocation-db.com/json/`);

    if (!response.ok)
      throw new Error(`Response status: ${response.status}`);

    const json = await response.json();

    return json;
  } catch (error: any) {
    console.error(`Error fetching data:`, error);
  }
}

and then I access the data in a component in the way the docs state:

export default function MyComponent({ loaderData }) {
  // do something with loaderData
}

So my issue/question is, on my main route pages, I am using the included meta functionality like so:

import type { Route } from "./+types/route-name";

export function meta({}: Route.MetaArgs) {
  // meta data
}

and I'd like to know if there is a way to somehow access that loaderData inside the meta function.

Hope that all makes sense. Thanks!

EDIT: CodeSandbox Link - might be an issue with CORS in viewing the actual data returned from the loaderData logic call (disabling CORS makes it work properly), but if any further explanation is needed, can do.


Solution

  • So I actually figured out a solution. The meta function takes certain parameters, and one of them is matches, and inside this matches parameter lies all sorts of information coming from the routes, and of those data points comes from the main layout route, which in my case is where the loaderData logic lies, so that data is available inside the array of objects return from the matches param natively available from meta.

    Thanks for looking at this @Drew Reese!

    export function meta({ matches }: Route.MetaArgs) {
      // find corresponding data in matches args
    }