useLoaderData not returning data from closest route

67 views Asked by At

I have the following problem with the React framework Remix. I understood that useLoaderData "Returns the serialized data from the closest route loader." as the docs say.

So I setup a very simple route

example.tsx
example._index.tsx
example.finish.tsx

I added a different text in each of them to make sure they were rendering correctly, and they were fine.

Then I tried to add a loader

My example.tsx looks like this:

import { Outlet } from "@remix-run/react";
import type { LoaderFunction } from "@remix-run/node";

export const loader: LoaderFunction = async () => {
  return {
    message: "Hello from the loader!"
  };
};

export default function Example() {
  return (
    <div>
      <h1>Layout</h1>
      <Outlet />
    </div>
  );
}

and in example._index.tsx

import { useLoaderData, Link } from "@remix-run/react";

export default function ExampleIndex() {
  const { message } = useLoaderData<{
    message: string;
  }>();

  return (
    <div>
      <h1>Example Index {message}</h1>
      <Link to="/example/finish">Finish</Link>
    </div>
  );
}

but now there is an error

TypeError: Cannot destructure property 'message' of 'useLoaderData3(...)' as it is null.

So it seems I understood the whole thing wrong, I assumed by using useLoaderData I could access the data loaded in the route loader.

Am I doing it wrong? Any help is much appreciated.

0

There are 0 answers