Help with fetching data from API ( New to Remix ) #9645
-
Hi everyone, I'm new to Remix.run and I'm having trouble understanding how to fetch data for my component. I've been following the documentation, but I'm still confused about how to properly load data on the server-side and pass it to my component. Here's what I'm trying to do: Fetch data from an API endpoint when my page loads. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Hey, this should be pretty simple Create a Use the Here's a simple example: import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
// 1. Define the loader function
export const loader = async () => {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
// Return the data using the `json` helper
return json(data);
};
export default function Index() {
// 2. Use the `useLoaderData` hook to access the data
const data = useLoaderData();
return (
<div>
<h1>Data from API</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
} Hope this helps :) |
Beta Was this translation helpful? Give feedback.
-
How about if deploy in cloudflare , it work in development but prod "Server Error" , in my case |
Beta Was this translation helpful? Give feedback.
Hey, this should be pretty simple
Create a
loader
function: This function will run on the server-side and fetch the data.Use the
useLoaderData
hook: This hook will allow you to access the data fetched by the loader function within your component.Here's a simple example: