jedidiah
jedidiah

Reputation: 1

How do I update entry in indexedDB without creating a new entry

I'm creating a basic contacts app to learn about IndexedDB and how to use it. I've read the Mozilla developer guide and it mentions updating entries but it doesn't seem to work for me. Any help would be greatly appreciated. Thanks

The success handler

let dbObject = window.indexedDB.open( 'contacts' );

The code for .onupgradeneeded

let peopleOS = db.createObjectStore( 'people', { keyPath: "name", autoIncrement: false } );

dbObject.onsuccess = e => {

    // Retreive database
    let db = event.target.result;

    /*
    * ---------------------------
    * Add one person to database
    * ---------------------------
    * 
    * Create Transaction
    * Select Object Store
    * Add Person
    */

    let trxn = db.transaction( ['people'], 'readwrite' );
    let store = trxn.objectStore( 'people' );

    store.add( { name: "Jedidiah", age: 20 } );
    store.add( { name: "Mario", age: 127 }  );

    trxn.oncomplete = () => {

        let trxn = db.transaction( ['people'], 'readwrite' );
        let store = trxn.objectStore( 'people' );

        // Update
        let request = store.get("Jedidiah");
        request.onsuccess = (event) => {

            let data = event.target.result;

            // Update name to "Ieti"
            data.name = "Ieti";

            let result = store.put( data );
            result.onsuccess = () => {
                alert("Value updated");
            };

        };

    };

};

I expect the entry with the name "Jedidiah" value to be changed to "Ieti" but instead it creates a new entry in the DB with same values as "Jedidiah" but with the name and keyPath being "Ieti"

Upvotes: 0

Views: 460

Answers (1)

Ujjwal Kumar Gupta
Ujjwal Kumar Gupta

Reputation: 2376

The put() method of the IDBObjectStore interface updates a given record in a database, or inserts a new record if the given item does not already exist. But if you want to update some property of the stored data like in your case, you should use update api.

Here is doc for put api - https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put

Here is doc for update api - https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update

Upvotes: 1

Related Questions