Forem

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

Posted on β€’ Edited on

2 1

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 🩡⭐

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly β€” using the tools and languages you already love!

Learn More

Top comments (0)

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay