How to manage data in localStorage of web-browsers? Explain with the JavaScript, React JS.
Tags: javascript, react, localstorage, browser
Published: 2022-04-08 11:06:53

First of all , let’s discuss localStorage. A localStorage is a property that allows JavaScript sites and apps to save key-value pairs in a web browser with no expiration date. The localStorage of web-browsers storage capacity is maximum 10 MB. LocalStorage data has no expiration date, until you delete the data from the localStorage. We can say localStorage holds the data permanently. The localStorage data provides better user experience during the surfing on web pages. Now We will explore this localStorage with shopping cart examples and also with the JavaScript library React JS code.

---
**Step 1: Get Data From localStorage**
Declare a variable name `shoppingCart` with empty object `let shoppingCart = {};` . Here, `let` keyword is used because variable values can be changed.Let’s write an arrow function name `addToDb` and pass a parameter called `id`(here id comes from product component) . Now rest of the code will be inside the arrow function .

Now we have to get the data from localStorage using `storedCart` Variable `const storedCart = localStorage.getItem(‘shopping-cart’);` and check with if condition whether the data is available in the `localStorage `or not, with the `storedCart `variable. If any data is found in localStorage then get the data using `JSON.parse()` method (`shoppingCart = JSON.parse(storedCart);`). Because basically data stored in localStorage as json format. That’s why we need to convert this data into a JavaScript object. I think you got the point, why the JSON.parse() method is used when getting the data from the localStorage. Else data is not found then set is am empty object (`shoppingCart = {}`).

```
const storedCart = localStorage.getItem('shopping-cart');
if (storedCart) {
    shoppingCart = JSON.parse(storedCart);
}
else {
    shoppingCart = {}
}
```

---

> Step 2: Add Quantity to the shopping Cart
This part will also be inside the `addToDb `arrow function.


Now Declare a variable name `quantity `which is assigned with `shoppingCart[id]` . then check the quantity with if condition whether any new quantity comes or not. `If `a new quantity comes then the quantity will be increased by 1. `Else `quantity will be set as 1.

Now finally set the data in shoppingCart and store in the localStorage with following code `localStorage.setItem(‘shopping-cart’, JSON.stringify(shoppingCart));`

Here we used `JSON.stringify` when setting the data in localstorage because we know, in local storage data is being stored in json format. For this reason we need to convert JavaScript objects to JSON format. That is why `JSON.stringify` is being used.

```
const quantity = shoppingCart[id];
if (quantity) {
    const newQuantity = quantity + 1;
    shoppingCart[id] = newQuantity;
}
else {
    shoppingCart[id] = 1;
}
localStorage.setItem('shopping-cart', JSON.stringify(shoppingCart));
```

---

> Step 3: Remove data from the shopping cart
Following code will help us to remove data from the shopping cart.

```
const removeFromDb = (id) => {
const storedCart = localStorage.getItem('shopping-cart');
if (storedCart) {
    const shoppingCart = JSON.parse(storedCart);
if (id in shoppingCart) {
    delete shoppingCart[id];
    localStorage.setItem('shopping-cart', JSON.stringify(shoppingCart));
}}}
```

---

> Step:4 Export this function for the display on UI product component

```
export { addToDb, removeFromDb };
```

---

> Full Source Code:

source code in `cartdb.js`

```
// Step1: Get Data From localStorage:
let shoppingCart = {};
const addToDb = (id) => {// get data from local storage
const storedCart = localStorage.getItem('shopping-cart');
if (storedCart) {
   shoppingCart = JSON.parse(storedCart);
}
else {
    shoppingCart = {}
}// Step2: Add Quantity to the shopping Cart:
const quantity = shoppingCart[id];
if (quantity) {
    const newQuantity = quantity + 1;
    shoppingCart[id] = newQuantity;
}
else {
    shoppingCart[id] = 1;
}
localStorage.setItem('shopping-cart', JSON.stringify(shoppingCart));
}// Step3: Remove data from the shopping cart
const removeFromDb = (id) => {
const storedCart = localStorage.getItem('shopping-cart');
if (storedCart) {
    const shoppingCart = JSON.parse(storedCart);
if (id in shoppingCart) {
    delete shoppingCart[id];
    localStorage.setItem('shopping-cart', JSON.stringify(shoppingCart));
}}}// Step:4 Export this function for the display on UI product component
export { addToDb, removeFromDb };
```

---

> source code in` Cosmetic.js`

```
import React from 'react';
import { addToDb, removeFromDb } from '../Utilities/cartdb';
import './Cosmetic.css'const Cosmetic = (props) => {
const { name, price, id } = props.cosmetic;const addToCart = (id) => {
    addToDb(id);
}const removeFromCart = (id) => {
    removeFromDb(id);
}return (
    <div className='product'>
    <h3>name: {name}</h3>
    <h4>Price: {price}</h4>
    <p>It has id: {id}</p>
    <button onClick={() => addToCart(id)}>Add to Cart</button>
    <button onClick={() => removeFromCart(id)}>Remove</button>
    </div>
);
};
export default Cosmetic;
```