⊗jsrtPmRtGSP 35 of 47 menu

Loading Page Data by URL Parameters from Store in React Router

Now we can add products to our application. Run the application, add a couple of products with a button. If we now click on the products themselves in the list, we will see that each product still has the same static page, which we will deal with in this and subsequent lessons.

There is one more thing to note. In general, the entire URL is divided into segments - these are parts of the URL between the / symbols. You probably remember that when creating this application, we specified the path 'products/:productId', so :productId is called here dynamic segment. The ':' symbol is placed before it. The values ​​in this segment will change, they are what get into the URL parameters (URL Params or params), which are passed to the loader under a certain key, in our case it will be params.productId.

Take a look at the address bar in the browser when you click on the products in the list. You will see that the last segment in the address bar changes, these are the values ​​that will be loaded into the loader. And our products in the storage have a unique id generated by us, so the product we need will be loaded.

And now, after a short digression, let's finally work with the product page, and more specifically, with loading data from storage.

Let's repeat the familiar process. First, in forStorage.js, we add the getProduct function to get data for a specific product from the storage by id. Here we already pass id to the function and, accordingly, if the product is "cached" for us, it will be displayed without delay:

export async function getProduct(id) { await someNetwork(`product:${id}`); }

Next, we need to get an array of products and find our product among them by the passed id:

export async function getProduct(id) { await someNetwork(`product:${id}`); let products = await localforage.getItem('products'); let product = products.find((product) => product.id === id); return product ?? null; }

Take the app you created in the previous lessons. Using the lesson materials, create a function forStorage.js getStudent to get the student data by id.

azrucsplid