Handling Browser Storage & Fetching and Displaying Data in JavaScript

Payal PorwalPayal Porwal
8 min read

Handling Browser Storage in JavaScript

In modern web development, storing data in the browser is essential for maintaining user preferences, session information, and more. JavaScript provides three main ways to store data in the browser:

  1. Local Storage – Stores data with no expiration.

  2. Session Storage – Stores data for a single session.

  3. Cookies – Stores small data with expiration and is sent to the server with each request.


1. Local Storage

What It Does:

  • Stores data permanently in the browser.

  • Data remains even after closing and reopening the browser.

  • Stores key-value pairs as strings.

Methods:

  1. localStorage.setItem("key", "value") – Stores data.

  2. localStorage.getItem("key") – Retrieves data.

  3. localStorage.removeItem("key") – Removes data.

  4. localStorage.clear() – Clears all stored data.

Real-Life Examples:

  1. Saving User Preferences (Theme Selection)

     document.getElementById("darkModeBtn").addEventListener("click", function() {
       document.body.classList.toggle("dark-mode");
       localStorage.setItem("theme", document.body.classList.contains("dark-mode") ? "dark" : "light");
     });
    
     // Load saved theme on page reload
     if (localStorage.getItem("theme") === "dark") {
       document.body.classList.add("dark-mode");
     }
    
  2. Saving User Login State

     function login() {
       localStorage.setItem("loggedIn", "true");
     }
     function checkLoginStatus() {
       if (localStorage.getItem("loggedIn") === "true") {
         console.log("User is logged in");
       }
     }
     checkLoginStatus();
    
  3. Storing Cart Items in an E-Commerce Site

     let cart = ["Product1", "Product2"];
     localStorage.setItem("cartItems", JSON.stringify(cart));
     console.log(JSON.parse(localStorage.getItem("cartItems"))); // Output: ["Product1", "Product2"]
    
  4. Remembering Last Visited Page

     localStorage.setItem("lastPage", window.location.href);
     console.log("You last visited:", localStorage.getItem("lastPage"));
    
  5. Saving Notes in a Text Editor

     document.getElementById("note").addEventListener("input", function() {
       localStorage.setItem("userNote", this.value);
     });
     document.getElementById("note").value = localStorage.getItem("userNote") || "";
    

2. Session Storage

What It Does:

  • Stores data temporarily (only until the tab is closed).

  • Works like local storage but clears automatically when the session ends.

  • Stores key-value pairs as strings.

Methods:

  1. sessionStorage.setItem("key", "value") – Stores data.

  2. sessionStorage.getItem("key") – Retrieves data.

  3. sessionStorage.removeItem("key") – Removes specific data.

  4. sessionStorage.clear() – Clears all data.

Real-Life Examples:

  1. Saving Temporary Form Data

     document.getElementById("name").addEventListener("input", function() {
       sessionStorage.setItem("username", this.value);
     });
     document.getElementById("name").value = sessionStorage.getItem("username") || "";
    
  2. Tracking User Progress in a Multi-Step Form

     sessionStorage.setItem("step", "2");
     console.log("Current Step: ", sessionStorage.getItem("step"));
    
  3. Storing User's Selected Filters on a Product Page

     sessionStorage.setItem("selectedCategory", "Electronics");
     console.log("Category: ", sessionStorage.getItem("selectedCategory"));
    
  4. Storing Scroll Position of a Page

     window.addEventListener("scroll", function() {
       sessionStorage.setItem("scrollPosition", window.scrollY);
     });
     window.scrollTo(0, sessionStorage.getItem("scrollPosition"));
    
  5. Remembering Open Tabs in a Dashboard

     sessionStorage.setItem("activeTab", "analytics");
     console.log("Currently Open Tab: ", sessionStorage.getItem("activeTab"));
    

3. Cookies

What It Does:

  • Stores small data (up to 4KB).

  • Data can expire after a set time.

  • Automatically sent with each HTTP request.

Methods:

  1. Creating a Cookie

     document.cookie = "username=John; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
    
  2. Reading a Cookie

     console.log(document.cookie);
    
  3. Deleting a Cookie

     document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
    

Real-Life Examples:

  1. Remembering User Preferences (Language Selection)

     function setLanguage(lang) {
       document.cookie = `language=${lang}; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/`;
     }
     console.log("Preferred Language:", document.cookie);
    
  2. Tracking User Behavior (Visited Pages)

     let visitedPages = document.cookie.replace(/(?:(?:^|.*;\s*)visited\s*=\s*([^;]*).*$)|^.*$/, "$1") || "";
     visitedPages += "Home, ";
     document.cookie = "visited=" + visitedPages;
     console.log("User visited: ", document.cookie);
    
  3. Auto Login Using Cookies

     document.cookie = "userToken=abc123; expires=Fri, 31 Dec 2025 23:59:59 GMT; path=/";
     if (document.cookie.includes("userToken")) {
       console.log("User is logged in");
     }
    

Conclusion

Storage TypeData PersistenceScopeMax SizeSent to Server
Local StoragePermanentAll Tabs~5MBNo
Session StorageUntil Tab ClosesSingle Tab~5MBNo
CookiesCustom ExpiryAll Tabs~4KBYes
  • Use local storage for long-term storage like user preferences.

  • Use session storage for temporary data like form progress.

  • Use cookies for data that needs to be sent to the server (e.g., authentication).

Understanding these storage methods helps in building efficient and user-friendly applications. 🚀

Fetching and Displaying Data in JavaScript

In modern web applications, fetching and displaying data dynamically is crucial for creating interactive and real-time user experiences. JavaScript provides the Fetch API, a powerful tool to retrieve data from a server and update the UI dynamically.


1. Fetch API

What It Does:

  • The Fetch API allows you to make HTTP requests (GET, POST, PUT, DELETE, etc.) to fetch data from an external source (APIs, servers, or files).

  • It returns a Promise, which can be handled using .then() for success and .catch() for errors.

  • Works asynchronously, meaning it does not block other operations.

Basic Syntax:

fetch('https://api.example.com/data')
  .then(response => response.json()) // Convert response to JSON
  .then(data => console.log(data)) // Handle the data
  .catch(error => console.error('Error fetching data:', error));

2. Fetching and Displaying JSON Data Dynamically

Example 1: Displaying a List of Users

Imagine you are creating a user list from an API.

fetch('https://jsonplaceholder.typicode.com/users')
  .then(response => response.json())
  .then(users => {
    const userList = document.getElementById('userList');
    users.forEach(user => {
      let li = document.createElement('li');
      li.textContent = `${user.name} - ${user.email}`;
      userList.appendChild(li);
    });
  })
  .catch(error => console.error('Error fetching users:', error));

HTML Code:

<ul id="userList"></ul>

🔹 Real-Life Use Case: Social media platforms use this technique to load friend lists or followers dynamically.


Example 2: Fetching Weather Data and Displaying it on a Dashboard

Let's say you want to fetch weather data and show it on your site.

fetch('https://api.weatherapi.com/v1/current.json?key=YOUR_API_KEY&q=London')
  .then(response => response.json())
  .then(data => {
    document.getElementById('weather').innerText = `Temperature: ${data.current.temp_c}°C, Condition: ${data.current.condition.text}`;
  })
  .catch(error => console.error('Error fetching weather data:', error));

HTML Code:

<p id="weather">Loading weather...</p>

🔹 Real-Life Use Case: Weather apps and dashboards fetch real-time weather data to keep users updated.


Example 3: Fetching Products and Updating UI

Imagine you are working on an e-commerce site and want to display products dynamically.

fetch('https://fakestoreapi.com/products')
  .then(response => response.json())
  .then(products => {
    const productList = document.getElementById('productList');
    products.forEach(product => {
      let div = document.createElement('div');
      div.classList.add('product');
      div.innerHTML = `<h3>${product.title}</h3><img src="${product.image}" width="100"><p>Price: $${product.price}</p>`;
      productList.appendChild(div);
    });
  })
  .catch(error => console.error('Error fetching products:', error));

HTML Code:

<div id="productList"></div>

🔹 Real-Life Use Case: E-commerce websites like Amazon fetch and display products dynamically to improve user experience.


3. Updating UI Based on API Responses

You can use the Fetch API to update the UI based on the data received from the server. This is useful for real-time updates, notifications, and live data rendering.

Example: Real-time Cryptocurrency Prices

function fetchCryptoPrice() {
  fetch('https://api.coindesk.com/v1/bpi/currentprice/BTC.json')
    .then(response => response.json())
    .then(data => {
      document.getElementById('cryptoPrice').innerText = `Bitcoin Price: $${data.bpi.USD.rate}`;
    })
    .catch(error => console.error('Error fetching crypto price:', error));
}

setInterval(fetchCryptoPrice, 5000); // Update every 5 seconds

HTML Code:

<p id="cryptoPrice">Loading Bitcoin Price...</p>

🔹 Real-Life Use Case: Stock market apps and crypto dashboards fetch real-time data and update UI dynamically.


Conclusion

Fetch API ConceptDescription
fetch(url)Makes an HTTP request
.then(response => response.json())Converts response to JSON
.catch(error => console.error(error))Handles errors
setInterval(fetchFunction, time)Fetches data repeatedly

Key Takeaways:

  • The Fetch API is a powerful tool for making HTTP requests to fetch data.

  • We can dynamically display JSON data using JavaScript.

  • Fetch API is widely used in real-world applications like weather updates, e-commerce product listings, and stock market apps.

🚀 Mastering the Fetch API will help you build interactive and data-driven web applications!

Here's a complete real-life working example using HTML, Bootstrap, and JavaScript to fetch and display data dynamically from an API.

Project Overview

This example will:
✅ Fetch and display user data dynamically from an API.
✅ Use Bootstrap for styling.
✅ Show a loading spinner while fetching data.
✅ Handle errors gracefully.


Full Code: Fetch API with Bootstrap UI

1️⃣ index.html

htmlCopyEdit<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fetch API Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

    <div class="container mt-5">
        <h2 class="text-center">User List (Fetched from API)</h2>

        <!-- Loading Spinner -->
        <div id="loading" class="text-center my-3">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>

        <!-- Users Data -->
        <div class="row" id="userList"></div>

        <!-- Fetch Button -->
        <div class="text-center mt-4">
            <button class="btn btn-primary" onclick="fetchUsers()">Fetch Users</button>
        </div>
    </div>

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

2️⃣ script.js (Fetch API with Bootstrap UI)

javascriptCopyEdit// Function to Fetch Users from API
function fetchUsers() {
    document.getElementById("loading").style.display = "block"; // Show loading spinner

    fetch('https://jsonplaceholder.typicode.com/users')
        .then(response => response.json()) // Convert response to JSON
        .then(users => {
            document.getElementById("loading").style.display = "none"; // Hide loading spinner
            const userList = document.getElementById("userList");
            userList.innerHTML = ""; // Clear previous data

            users.forEach(user => {
                const userCard = document.createElement("div");
                userCard.classList.add("col-md-4", "mb-3");
                userCard.innerHTML = `
                    <div class="card shadow-sm p-3">
                        <h5 class="card-title">${user.name}</h5>
                        <p class="card-text"><strong>Email:</strong> ${user.email}</p>
                        <p class="card-text"><strong>Phone:</strong> ${user.phone}</p>
                        <p class="card-text"><strong>Website:</strong> <a href="https://${user.website}" target="_blank">${user.website}</a></p>
                    </div>
                `;
                userList.appendChild(userCard);
            });
        })
        .catch(error => {
            document.getElementById("loading").style.display = "none"; // Hide loading spinner
            console.error('Error fetching users:', error);
            document.getElementById("userList").innerHTML = "<p class='text-danger text-center'>Failed to load users. Try again.</p>";
        });
}

💡 How It Works?

  1. The Fetch Users button calls the fetchUsers() function.

  2. The loading spinner appears while fetching data.

  3. The Fetch API gets user data from https://jsonplaceholder.typicode.com/users.

  4. The response is converted to JSON and dynamically added to the UI.

  5. If an error occurs, a message is shown instead of data.


🎯 Features in this Code:

Bootstrap-styled UI for a professional look.
Dynamic data rendering using JavaScript.
Error handling for failed API calls.
Loading spinner while fetching data.

This is a real-world approach used in websites to fetch and display API data dynamically. 🚀 Let me know if you need any modifications! 😊

10
Subscribe to my newsletter

Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Porwal
Payal Porwal

Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟