Creating a Route to Edit Data in React Router
In the previous lesson we created an editing form in a separate React component EditProduct.
Let's now write a loader function for the new route right after the import and before the EditProduct function. It will be the same as in product.jsx. The function will receive URL parameters and then we will get the product by its id:
export async function loader({ params }) {
const product = await getProduct(params.productId);
return { product };
}
Import getProduct from forStorage.js:
import { getProduct } from '../forStorage';
Now we'll open our main.jsx and import the EditProduct component we created and the loader:
import EditProduct, { loader as editProductLoader } from './routes/edit';
Then we add the edit route object to the children array, right after the product route:
children: [
{
path: 'products/:productId',
element: <Product />,
loader: productLoader,
},
{
path: 'products/:productId/edit',
element: <EditProduct />,
loader: editProductLoader,
},
],
Now let's launch the application, create a product, click on it, then on the edit button and see our form.
The only thing we need to do is to make sure that the current data is loaded into the form fields before editing. To do this, we import the useLoaderData hook into edit.jsx:
import { Form, useLoaderData } from 'react-router-dom';
And we will use it to get data from the loader in the EditProduct function. We will add it before the return command:
const { product } = useLoaderData();
Now let's add the defaultValue attribute to each input tag with the corresponding values for each input. For example, the first input will now look like this:
<input
placeholder="name"
type="text"
name="name"
defaultValue={product.name}
/>
For the two remaining inputs, the values will be 'product.cost' and 'product.amount', respectively. However, we don't have any data in the form yet.
Take the app you created in the previous lessons. Using the lesson materials, create a loader function in edit.jsx for the student data editing route.
Add the route object to the children array for editing.
Add the code required in the lesson to your EditStudent function.