DEV Community

Kamrul Hasan
Kamrul Hasan

Posted on

How to manage data in localStorage of web-browsers? Explain with the JavaScript, React JS.

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 localStorageor not, with the storedCartvariable. 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 = {}
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Quantity to the shopping Cart
This part will also be inside the addToDbarrow function.

Now Declare a variable name quantitywhich is assigned with shoppingCart[id] . then check the quantity with if condition whether any new quantity comes or not. Ifa new quantity comes then the quantity will be increased by 1. Elsequantity 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));
Enter fullscreen mode Exit fullscreen mode

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));
}}}
Enter fullscreen mode Exit fullscreen mode

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

export { addToDb, removeFromDb };
Enter fullscreen mode Exit fullscreen mode

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 };
Enter fullscreen mode Exit fullscreen mode

source code inCosmetic.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;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)