Route Data Loader in React Router
In the previous lesson, we retrieved the product data from the store. Now this data needs to be loaded into the route element. To do this, we use the loader function. We will create it now.
Let's open root.jsx, add here the import line getProducts from forStorage.js:
import { getProducts } from '../forStorage'
Right after the import lines and before the Root function, we will write the code for the loader function, which will return data with products from the storage via getProducts. In general, such functions should be written in a separate file, but we will be a little lazy, so do not pay attention to the warning:
export async function loader() {
const products = await getProducts();
return { products };
}
Let's now add an import for our loader to main.jsx. We'll have this loader for the root, so let's call it rootLoader:
import Root, { loader as rootLoader } from './routes/root';
And let's add it to our route object in the loader property:
const router = createBrowserRouter([
{
path: '/',
element: <Root />,
errorElement: <ErrorPage404 />,
loader: rootLoader,
children: [
{
path: 'products/:productId',
element: <Product />,
},
],
},
]);
Take the app you created in the previous lessons. Using the lesson materials, write a function loader in the root.jsx file to load the student data and add it to the route object in main.jsx.