Getting Data from Store in React Router
You can see that our application is static for now. In this and subsequent lessons, we will start to animate it. In the next lessons, we will be able to add products to the list using React Router.
In this lesson, we will first figure out how to get data from storage. For local data storage, we will use localForage storage (you can read about its use and advantages in the documentation) - an analogue of LocalStorage, which is supported by all modern browsers. In fact, this is a combination of several storage technologies. With relatively easy use, it allows you to store large amounts of data, and of different types, including images. Let's install it in our project. Type in the terminal:
npm i localforage
Let's restart our application. In the src folder, we will create a forStorage.js file, which will contain functions for working with storage.
So, let's start with the function for loading products from storage. Let's add the library import to forStorage.js and write the function getProducts to get products:
import localforage from 'localforage';
export async function getProducts() {
await someNetwork();
let products = await localforage.getItem('products');
if (!products) products = [];
return products;
}
Below after the function code we will also add code for someNetwork, simulating network delays (up to 0.7 seconds) for normal operation of functions. If our product is "cached", then there will be no delay in the functions for working with the storage, if not, then there will be a delay, you will see later how this works:
let someCache = {};
async function someNetwork(key) {
if (!key) {
someCache = {};
}
if (someCache[key]) {
return;
}
someCache[key] = true;
return new Promise((res) => {
setTimeout(res, Math.random() * 700);
});
}
Take the application you created in the previous lessons. Install localForage storage in the application.
Using the lesson materials, create a file forStorage.js and write a function getStudents in it to get student data from the storage.