Skills
Programming
Indexeddb

Indexed Database (Local Browser DB)

This code demonstrates the usage of the IndexedDB API in a React application. IndexedDB is a built-in browser API that allows you to store and retrieve data in a structured way, similar to a client-side database. It's useful for handling large amounts of data and providing a better user experience by enabling offline functionality.

To be able to monitor created DB Right Click on the page Inspect > Application > IndexedDB there you will see Cars database I use as an exemple, created.

TRY ME!

All the elements that are stored in your local Indexed database listed below.

    Importing Dependencies: The code imports the necessary React hooks (useEffect and useState) and a CSS module file (styles/indexedDB.module.css) for styling.

    indexedDB.tsx
    import React, { useEffect, useState } from 'react';
    import styles from './indexedDB.module.css'

    Functional Component: The IndexedDB component is a functional component in React. It uses the useState hook to manage the state of Vehicle Color, Model, and listItems.

    indexedDB.tsx
    const IndexedDB: React.FC = () => {
        const [colour, setColour] = useState('');
        const [make, setMake] = useState('');
        const [listItems, setListItems] = useState([]);
     

    useEffect Hook:

    • The useEffect hook is used to create and open an IndexedDB database named "Cars" with version 1. It runs only once during the component's initial render.
    • Inside the useEffect hook, the code checks if the window object is defined (to ensure it's running on the client-side) and opens the IndexedDB database.
    • If the database doesn't exist, the onupgradeneeded event is triggered, where an object store named "cars" is created. An object store is like a table in a traditional database, and it stores the actual data.
    • Two indexes are created for the "cars" object store: car_colours (for searching by color) and colour_and_make (for searching by color and make).
    indexedDB.tsx
    useEffect(() => {
            if (typeof window !== 'undefined') {
                const indexedDB = window.indexedDB;
                const request = indexedDB.open('Cars', 1);
                request.onerror = (event) => {
                    console.log('Error: ', event);
                };
     
                request.onupgradeneeded = (event) => {
                    const db = (event.target as IDBOpenDBRequest).result;
                    const store = db.createObjectStore('cars', { keyPath: 'id', autoIncrement: true });
                    store.createIndex('car_colours', ['colour'], { unique: false });
                    store.createIndex('colour_and_make', ['colour', 'make'], { unique: false });
                };
            }
        }, []);

    Form Submission Handler: The handleSubmit function is called when the form is submitted. It prevents the default form submission behavior using event.preventDefault().

    indexedDB.tsx
    const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
            event.preventDefault();

    Opening the IndexedDB Database: Inside the handleSubmit function, the code opens the IndexedDB database named "Cars" with version 1

    indexedDB.tsx
            const request = indexedDB.open('Cars', 1);
     

    Storing Data in IndexedDB: When the database is opened successfully (request.onsuccess), the code performs the following steps: Creates a read-write transaction on the "cars" object store. Retrieves all keys from the object store using store.getAllKeys(). Finds the maximum key value from the retrieved keys. Calculates the next available key value by incrementing the maximum key value by 1. Stores the new data object in the object store using `store.put().

    Retrieving Data from IndexedDB: After storing the data, the code retrieves all data from the object store using store.getAll(). Rendering the Data: When the data is retrieved successfully (getAllDataRequest.onsuccess), the code maps over the retrieved data and creates an array of li elements, each representing a data item with its colour and make properties.

    indexedDB.tsx
    request.onsuccess = () => {
                const db = request.result;
                const transaction = db.transaction('cars', 'readwrite');
                const store = transaction.objectStore('cars');
     
                // Get all keys from the object store
                const getAllKeysRequest = store.getAllKeys();
                getAllKeysRequest.onsuccess = () => {
                    const keys = getAllKeysRequest.result;
                    // Find the maximum key
                    const maxId = keys.reduce((acc, curr) => (curr > acc ? curr : acc), -1);
                    const nextId = (maxId as number) + 1;
     
                    store.put({ id: nextId, colour, make });
     
                    const getAllDataRequest = store.getAll();
                    getAllDataRequest.onsuccess = () => {
                        const data = getAllDataRequest.result;
                        // Render the data in li tags
                        const listItems = data.map((item: any) => <li key={item.id}>{item.colour} - {item.make}</li>);
                        // Set the listItems to state or use it directly in your component
                        setListItems(listItems);
                    };
                };
            };
        };