Parametrize Route Loader for Nested Route in Tanstack Router

In this lesson, we learn how to parametrize the loader for a nested route in TanStack Router.

We focus on a nested route like /employees/$employeeId, where the $employeeId is a dynamic parameter.

To fetch data for this route, we use a loader function that accesses the $employeeId parameter. This is achieved by using the params object available in the loader function, which contains the dynamic segments of the URL. We then use this parameter to call a function like getEmployeeById, which fetches specific employee details from an API.

We highlights that TanStack Router automatically infers types for these parameters, ensuring type safety for nested routes.

Share with a coworker

Transcript

[00:00] Here we are in the nested employees slash employee ID route. And I have provided some markup that is being displayed over here, the details of a certain employee. Now, again, this is hard-coded. So let's remove the hard code and let's provide a loader. Now this loader needs to be parameterized since we need to rely on what actually is this employee ID.

[00:26] So we're going to use the other function, the getEmployeeById. And as we can see, it's just going to shoot a request to employees slash ID from the mock API. And let's walk back to the component. So what we want to do over here is to obtain what actually is this ID. And when we run the loader we have access to lots of information over here and the one that is interesting to us is actually the parameters.

[00:56] So let's see what do we have in these parameters. Obviously it's the employee ID So imagine how many information is being automatically inferred on TypeScript level on the types of TANstack Router. So essentially we need to run the getEmployeeById function and this one is requiring a number. Now here in the root everything is a string obviously so we need to cast it into a number in whatever way we want. Now, since this ID is already a number, we can just run the function.

[01:38] Now this needs to be returned from the function. So now we can remove the hard code, but also use the route, the use loader data over here. So let's walk back again to our application. So let's walk to home, let's walk to employees. Now we are on the top level route of the employees, so just this one, and after clicking John Herzog, there is a new request that has been run for this nested route.