Getting Loader Data via URL Parameters in React Router
In the last lesson we wrote a function to get the product page data, let's import getProduct in the product.jsx file:
import { getProduct } from '../forStorage';
Let's write the loader function loader right after import and before the function Product. Let's pass the URL parameters to it:
export async function loader({ params }) {
const product = await getProduct(params.productId);
return { product };
}
We also import the useLoaderData hook to use the data received by the loader:
import { useLoaderData } from 'react-router-dom';
Let's apply useLoaderData, respectively replacing the line with the creation of the product object at the beginning of the Product function with the following:
const { product } = useLoaderData();
And, of course, we'll change our layout a little, since we've removed the old product object. We'll replace the contents of the paragraphs:
<p>Name: {product.name}</p>
<p>Cost: {product.cost}</p>
<p>Amount: {product.amount}</p>
To the following:
<p>Name: {product.name ? product.name : <i>unnamed</i>}</p>
<p>Cost: {product.cost ? product.cost : <i>unknown</i>}</p>
<p>Amount: {product.amount ? product.amount : <i>unknown</i>}</p>
All we have left to do is open main.jsx and add the import loader there, let's call it productLoader:
import Product, {
loader as productLoader,
} from './routes/product';
And register it as a loader for the product page route object, adding it to children after the element property:
children: [
{
path: 'products/:productId',
element: <Product />,
loader: productLoader,
},
],
That's it, we've sorted out loading data for the product page! However, we have nothing to load yet. Run the application, add products and click on them in the list to make sure everything works.
Take the application you created in the assignments for the previous lessons. Using the lesson materials, implement loader, connect it, use the data from it for the page with the student.