DEV Community

Cover image for Local Storage (Browser Object Module) in JS
Pranesh Chowdhury for Pranesh CodeCraft

Posted on • Updated on

Local Storage (Browser Object Module) in JS

Local Storage is a feature that enables JavaScript sites and apps to store key-value pairs in a web browser with no expiration date. This means that the data stored in the browser will persist even after the browser window is closed.

Five methods used for local storage:

setItem() = This method is used to add keys and values to the local storage.
getItem() = This method is used to get items from the local storage.
removeItem() = This method is used to remove an item from the local storage buy key.
clear() = This method is used to clear the local storage.
key() = This method is used to retrieve a key of local storage by passing a number.

Below this is a small project to understand Local storage.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input id="product-name" type="text" placeholder="product">
    <input id="product-quantity" type="text" placeholder="quantity">
    <button onclick="addProduct()">Add product</button>
    <ul id="product-container">

    </ul>
    <script src="product.js"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

JavaScript:

const addProduct = () => {
    const productField = document.getElementById('product-name');
    const quantityField = document.getElementById('product-quantity');
    const product = productField.value;
    const quantity = quantityField.value;

    productField.value = '';
    quantityField.value = '';

    console.log(product, quantity);
    displayProduct(product, quantity);
    saveProductToLocalStorage(product, quantity);
}

const displayProduct = (product, quantity) => {
    const ul = document.getElementById('product-container');
    const li = document.createElement('li');
    li.innerText = `${product}: ${quantity}`;
    ul.appendChild(li);
}


const getStoredShoppingCart = () => {
    let cart = {};
    const storedCart = localStorage.getItem('cart');
    if (storedCart){
        cart = JSON.parse(storedCart);
    }
    return cart;
}

const saveProductToLocalStorage = (product, quantity) => {
    const cart = getStoredShoppingCart();
    cart[product] = quantity;
    const cartStringified = JSON.stringify(cart);
    localStorage.setItem('cart', cartStringified);          // save into the local storage. 
}

// Display the html 
const displayProductsFromLocalStorage = () => {
    const savedCart = getStoredShoppingCart();
    console.log(savedCart);
    for (const product in savedCart){
        const quantity = savedCart[product];
        console.log(product);
        displayProduct(product, quantity);
    }
}

displayProductsFromLocalStorage();
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 🩵⭐

Top comments (0)