Adding Data to the Store in React Router
In this lesson we will be adding a product to the store. First, we need a function createProduct to create a product, let's add it to forStorage.js after the function getProducts:
forStorage.jsexport async function createProduct() {}
First, we add someNetwork again:
forStorage.jsexport async function createProduct() {
await someNetwork();
}
Now we will need a unique id for each product, you have already encountered this in the React tutorial. Let's use the nanoid library for this. Enter the following command in the terminal:
terminalnpm install --save nanoid
Import into forStorage.js library:
forStorage.jsimport { nanoid } from 'nanoid'
Let us have id by 6 characters:
forStorage.jsexport async function createProduct() {
await someNetwork();
let id = nanoid(6);
}
Initially, when creating a product, we will only have id in the object. Let's call getProducts, add the generated product and update the list of our products in the storage. Done:
forStorage.jsexport async function createProduct() {
await someNetwork();
let id = nanoid(6);
let product = { id };
let products = await getProducts();
products.unshift(product);
await setProducts(products);
return product;
}
The function for updating the list in the storage will be the following (we will add products to it under the key products), we will place it after the function createProduct:
forStorage.jsfunction setProducts(products) {
return localforage.setItem('products', products);
}
Take the app you created in the previous lessons. Using the lesson materials, write a function in forStorage.js createStudent and setStudents to add student data to the storage.