Deleting Data from Store in React Router
Our application can add new products, edit data, all that remains is to add data deletion. To do this, we will go through the steps familiar to us from previous lessons again.
First, let's open the forStorage.js file and add one last function to delete a specific product deleteProduct by its id:
export async function deleteProduct(id) {}
Then we get the list of products from the store and find the index of the product we want to remove, if such a product exists, we remove it from the list using splice. Next, we call setProducts and upload the new list of products to the store:
export async function deleteProduct(id) {
let products = await localforage.getItem('products');
let index = products.findIndex((product) => product.id === id);
if (index > -1) {
products.splice(index, 1);
await setProducts(products);
return true;
}
return false;
}
Take the application you created in the previous lessons. Using the lesson materials, write a function deleteStudent to delete student data from the storage by id.