Updating Data with FormData in React Router
We have a function updateProduct to update the product data in the store. Now let's move on to the data from our edit form.
When sending an HTML form, the browser creates a FormData object with data and sends it in the body of the request to the server. Moreover, the value of each input is extracted into the object from the name attribute (that's why we needed them in the form, remember?). Now we know that React Router sends requests not to the server, but to the action method of our route, so FormData will end up there. Let's work with this.
First, let's open our file edit.jsx and import updateProduct:
import { updateProduct } from '../forStorage';
Next, we'll write a function for the action route object, just like we did before. We'll add it right after the loader function. We'll pass it our request and URL parameters:
export async function action({ request, params }) {}
From the request we get FormData, then we extract the data from it as an object containing key:value pairs and use updateProduct to send this data to the store:
export async function action({ request, params }) {
const formData = await request.formData();
const updates = Object.fromEntries(formData);
await updateProduct(params.productId, updates);
return 1;
}
All that's left is to go to main.jsx and add the action function to the edit route object. Import action:
import EditProduct, {
loader as editProductLoader,
action as editAction,
} from './routes/edit';
And let's add it to the edit route object:
{
path: 'products/:productId/edit',
element: <EditProduct />,
loader: editProductLoader,
action: editAction,
},
Now run the application, add a couple of products to the list, then click on them to fill out the form and click the save button. Don't forget to go to the developer panel in the localforage section and update the storage. Now in the keyvaluespairs section we can see objects in the products array with our entered data.
Take the app you created in the previous lesson. Using the lesson materials, create a function action for the student data edit route, add it to the edit route object. Open the developer panel and verify that when you make changes, the updated data actually appears in the localforage tab.