#Use loader data in nested resource route

1 messages · Page 1 of 1 (latest)

digital axle
#

Hello! Let me explain without further a due:

Assuming routes set up in this way:

const routes = [
  layout('api/middleware.tsx', [
    index('routes/index.tsx'),
    route('/api/test', 'api/test.tsx'),
  ]),
];

Where api/middleware.tsx uses an Outlet to pass data down to any route that may need the data:

export const loader = () => {
  return { hello: 'world' };
};

const Middleware = () => {
  const data = useLoaderData<typeof loader>();

  return <Outlet context={data} />;
};

export default Middleware;

And routes/index.tsx can use the data from middleware's loader with the outlet's context:


const Index = () => {
  const data = useOutletContext();

  // this should render something saying {"hello": "world"}
  return (
    <div>do something with {JSON.stringify(data)}</div>
  );
};

export default Index;

Lastly, api/test.tsx is a resource route:

export const loader = () => {
  const data = // somehow get `middleware`'s data;
  return { ...data, foo: 'bar' };
};

The question is: given api/test.tsx is a nested route within api/middleware.tsx, is there any way that test's loader can access whatever data was returned from api/middleware.tsx?

#

Use loader data in nested resource route

lavish moss
#

I don't think it's possible, cause loaders run in parallel

#

even if they didn't, loaders run "outside" of react, so you wouldn't have access to any context

#

if you're starting a new project, you may want to look into the unstable middleware feature of RR7, which should give you what you're looking for

digital axle
#

that's actually exactly what i'm looking for, although i don't think i want to depend on a unstable feature. i'll refactor some code and take the small duplication hit for the time being. hope it makes it as a stable feature soon! thanks

lavish moss
#

you're welcome, fwiw, I think I saw that they were planning to stabilize it in the next few months