Fetching a Single User
Introduction: Why Fetch a Single Item?
Welcome back! In the previous lesson, you learned how to create new users using the POST method in a Remix route. Now, let’s look at another common task: fetching a single item, such as a user, by its unique identifier.
In real-world applications, you often need to display details for a specific item. For example, when you click on a user’s name in a list, you expect to see their profile page. To make this work, your backend needs to handle requests for a specific user and return only that user’s data.
In this lesson, you will learn how to set up a dynamic route in Remix to fetch a single user by their ID. This is a key skill for building APIs that support user profiles, product pages, and more.
Quick Recap: App Structure and Mock Data
Before we dive in, let’s quickly remind ourselves of the setup you already have. You have a Remix project with a route for users and a mock array of user data. Here’s a summary of the relevant parts:
You do not need to set this up again, but keep in mind that the users array is our mock database for this lesson.
Dynamic Routes in Remix
To fetch a single user, we need a way to handle requests like /api/users/2, where 2 is the user’s ID. Remix makes this easy with dynamic route segments.
A dynamic route in Remix uses a dollar sign in the file name to capture part of the URL as a parameter. For example:
In this case, $id means any request to /api/users/<some-id> will be handled by this file, and the <some-id> part (like 2, 17, or 99) will be available as a parameter named id.
This allows us to write code that responds to requests for any user, not just a specific one.
Building the GET Handler for a Single User
Let’s look at the code for handling a GET request to fetch a single user by ID. Here is the complete handler:
Let’s break down what’s happening here:
- We import the
usersarray and the necessary Remix helpers. - The
loaderfunction is called when a GET request is made to/api/users/:id. - We extract the
idfrom the URL usingparams.idand convert it to a number withNumber. - We search the
usersarray for a user with a matchingid. - If the user is found, we return their data as JSON.
- If the user is not found, we return a JSON error message with a 404 status.
