The server-side image in the Remix is failing to load, and the fetch operation is returning null within the child component

https://i.sstatic.net/sjfmr.pngI recently came across a tutorial here that showed me how to render an image from the server side. The code I tried 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 />
    </>
  );
}

While this code works perfectly in the _index.tsx file as expected, when I try to use it within another component, such as a contact-us component inside the _index.tsx file, it doesn't work and returns null.

Since I need to load a different image for my contact-us component, I tried using useLoaderData() inside it but it also returned null.

Is there a way to use different useLoaderData() for multiple components under the same route? Or is there a better approach I should consider?

Answer №1

Ensure that your loader and action functions provide a Response.

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",
    },
  });

  // Alternatively

  return json(data);
}

For more information, visit:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

bespoke numerical values within the Ionic 2 spectrum

The usual ionic range has a set minimum and maximum value for the possible range of values. <ion-range min="1" max="20" ...> However, I am in need of a custom range where the slider should only allow these specific values: {1, 5, 7, 20}. Is there ...

Unable to exclude modules from ng-build in Angular CLI, the feature is not functioning as intended

I am managing an Angular CLI project that consists of two identical apps. However, one app requires the exclusion of a specific module in its build process. Key Details: Angular CLI Version: 1.7.4 Angular Version: 5.2.10 In the angular-cli.json ...

Tips for identifying the characteristics of a mobx observer in the developer console of a web browser

Within the project I am currently involved in, there is heavy reliance on dependency injection. In this context, you will come across code structures similar to the following: type BigWidget = { title: string, } const AProps = { b: BigWidget } cl ...

What is the simplest way to obtain the TypeScript type of a prop for a React Native element?

Lately, I've noticed that I've been creating custom wrapper components for react native elements quite frequently. // MyButton.tsx import { TouchableWithoutFeedback } from "react-native" interface Props { onPress: () => void } //... <T ...

Tips for validating that a TypeScript parameter is a union with a specific type

Is there a way to create a TypeScript function that confirms an argument is a union type containing another, more specific union? Here's an example scenario: type Command = { name: string [key: string]: any } type Insert = { name: 'insert ...

Dealing with an endless update loop in React using useCallback and handling exhaustive dependencies in react-hooks

Take a look at this example that showcases a series of iframes being rendered. The goal is to save all the documents from the displayed iframes in the variable frames. import React, { useState, useEffect, useCallback } from "react"; import Frame, { Frame ...

Issue with React: when the onClick event is triggered, grab the value of the last variable and keep track of

const CharacterList = () => { const [change, setChange] = React.useState(false); const QuickSilver= () => setChange(!change); const SuperMan= () => setChange(!change); return ( <div id="character" className="list"> ...

The entry of 'number' cannot be replaced with 'string' in type.ts(2322)

Check out this code snippet: {animals.map((animal: Array<any>, i: number) => { return <span id={i} className={index === i ? "animal active" : "animal"} onClick={handleAnimalSelect}></span>; })} An issue has been ...

Storing data from a service into an array in Angular: Best practices

I have a service that provides getter and setter methods, returning id: number and title: String values from my dialog component. I am trying to save these responses into my data array but struggling to achieve it. For instance: 0: {id: 0, title: &qu ...

The main module's postinstall process is initiated before the sub-module's postinstall process

Update: I am seeking guidance on how to install a module from GitHub instead of npm. That's the main query. In case you're wondering why: I'm currently working on some confidential projects and prefer not to publish the code. As a result, ...

Is there a way to enable live-reload for a local npm package within a monorepo setup?

Currently, I am in the process of setting up a monorepo workspace that will house a Vue 3 application (using vite and TypeScript), cloud functions, and a shared library containing functions and TypeScript interfaces. I have successfully imported my local ...

Troubleshooting: Angular 13 input radio not recognizing checked condition

Storing selectedKitchenId in localstorage, and checking if selectedKitchenId === kitchen.id to determine which radio button should be selected. Cannot figure out why the checked condition is not working as expected, even though when I use a strong tag to d ...

How can I incorporate TypeScript paths into Storybook with Webpack version 5?

Storybook includes a pre-configured Webpack setup. Up until Webpack v4, it was possible to utilize tsconfig-paths-webpack-plugin and define custom tsconfig (or any other plugin) like so: const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plug ...

Combine values from 2 distinct arrays nested within an array of objects and present them as a unified array

In my current array, the structure looks like this: const books[{ name: 'book1', id: '1', fromStatus: [{ name: 'Available', id: 1 }, { name: 'Free', id: 2 }], t ...

Prevent the immediate response to the initial state change in React when a second change is made, especially when

Scenario: Working with a state called usersData that updates whenever the user applies filters to their data. The process of querying and updating this large object can be time-consuming. When a user triggers the filter change change1, it takes around 5 s ...

What is the method for obtaining the dynamic key of an object?

Is there a way for me to access the value of record.year dynamically? It seems like using record["year"] should give me the same result. I am trying to make my chart adaptable to different x-y axis configurations, which is why I am using fields[0] to retr ...

Utilizing TypeScript with Vue3 to Pass a Pinia Store as a Prop

My current stack includes Typescript, Pinia, and Vue3. I have a MenuButton component that I want to be able to pass a Pinia store for managing the menu open state and related actions. There are multiple menus in the application, each using the same store f ...

Is there a way to prevent the splash screen from appearing every time I navigate using a navbar link in a single page application (SPA)?

Recently, I came across this tutorial and followed it diligently. Everything seemed to be working perfectly until I encountered an issue with my navbar links. Each time I clicked on a link, the splash screen appeared, refreshing the page without directing ...

Prisma MongoDB adds new data to an existing array

When attempting to add new data to an array, I encountered an error. Strangely enough, the creation is successful when the array is empty, but once it contains data, I get the following error message: - error Error: Invalid `prisma.user.update()` invocat ...

Using NextJS App Router to implement redirects within the useEffect hook

I'm currently working on a Next.js 13.4.9 project and encountering an issue with redirecting logged in users within a client component using the useEffect hook. Despite trying a specific method, I keep getting an error in the browser (NEXT_REDIRECT). ...