⊗jsrtPmRtADA 34 of 47 menu

Adding data with the action method in React Router

In this lesson, we'll learn about the action method of the route object. This method is called when the application sends an HTTP request of type POST, PUT, PATCH, or DELETE (except GET) to your route.

First, let's import the product creation function we wrote in the last lesson into our root.jsx:

import { createProduct } from '../forStorage';

Now we need to create a function action that will be called by React Router when the add product button is clicked, let's place it after the function loader:

export async function action() { const product = await createProduct(); return { product }; }

Let's open main.jsx and import action:

import Root, { loader as rootLoader, action as rootAction } from './routes/root';

And we'll set it as the value of the action method for the route object. The Form component will prevent the browser from sending requests to the server when the button is clicked, but will instead call the action method of our route. This is how client-side routing works with React Router:

const router = createBrowserRouter([ { path: '/', element: <Root />, errorElement: <ErrorPage404 />, loader: rootLoader, action: rootAction, children: [ { path: 'products/:productId', element: <Product />, }, ], }, ]);

Let's run our application. Open the 'Application' tab (Application for Chrome) on the developer panel, among the different types of storage, click on indexedDB, here we are interested in localforage. Now, by clicking on the button to add products in our application and updating the localforage storage after the click, we see how objects with different id are added to the keyvaluepairs array products. Victory!!! This means that records are being created in our storage! Of course, the list in our application is also replenished. Hint: do not forget to clear the saved data of this page on the 'Storage' tab in Application.

Take the application you created in the previous lessons. Using the lesson materials, create a function action, add it to the root route object as a method action.

English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline