In this tutorial, we'll learn how to use the Loader function to fetch data from an external API in Remix.
You can use Loader function to send data to the route when rendering the page. This function only run on the server-side and not on the client-side.
That means that you can use it to fetch data from an external API or database and send it to the route.
We'll use the universities API to fetch a list of universities in the United Kingdom and display the list in our app.
Let's add a new route to our app called /universities
.
Add the following code to app/routes/universities.tsx
:
import type { LoaderArgs } from "@remix-run/node";
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
// Type to describe the data we get from the API
type University = {
name: string;
domains: string[];
};
// Loader function to fetch data from the API.
// This function only run on the server-side.
export const loader = async (args: LoaderArgs) => {
const response = await fetch(
"http://universities.hipolabs.com/search?country=United+Kingdom"
);
const universities: University[] = await response.json();
// Return the data as JSON
return json({ universities });
};
export default function Universities() {
// Get the data from the Loader function
const { universities } = useLoaderData<typeof loader>();
return (
<>
<h2>
List of universities in the United Kingdom ({universities.length})
</h2>
<ul>
{universities.map((university) => (
<li key={university.name}>
<a
href={`https://${university.domains[0]}`}
target="_blank"
rel="noreferrer"
>
{university.name}
</a>
</li>
))}
</ul>
</>
);
}
More Articles
- Use Remix Action to handle form submission
- Use Remix Loader to fetch data from an external API
- Validating form data in Remix using Zod and Action function
- Add a search form in Remix with data fetching
- Show a flash message in Remix after form submission
- Discover the best SaaS Starter Kits based on Remix