Remix server side image is not loading and fetch is returning null inside child component

263 views Asked by At

enter image description hereI was following the tutorial here to render an image from server side my code looks something like this

import { Outlet, useLoaderData } from '@remix-run/react';

export async function loader() {
  const response = await fetch('https://picsum.photos/500/300');
  return {
    imageUrl: response.url,
  };
}

export default function RandomImageLayout() {
  const imageData = useLoaderData<typeof loader>();

  return (
    <>
      <img
        src={imageData.imageUrl}
        alt="Random Image"
        style={{ maxWidth: '100%' }}
      />
      <Outlet />
    </>
  );
}

The code works when i am using it in the _index.tsx because i am accessing the route data using useLoaderData.

But the same code when used inside a component say a contact-us component inside the _index.tsx it won't work and returns null

since i want to load a different image for my contact-us component i wanted to use useloaderData() inside it and it returns null

How can i use differnt useLoaderData() for multiple componets under the same route?

Or is there any other approach?

1

There are 1 answers

0
Abe On

You need to return a Response from your loader and action.

import { json } from "@remix-run/node";

export async function loader() {
  const response = await fetch('https://picsum.photos/500/300');
  const data = { imageUrl: response.url }

  return new Response(JSON.stringify(data), {
    headers: {
      "Content-Type": "application/json",
    },
  });

  // OR SIMPLY

  return json(data);
}

Learn More: https://remix.run/docs/en/main/route/loader