Search code examples
javascriptupdatesauto-incrementindexeddb

How to update an IndexedDB item with autoincrement key?


I created an object store with autoIncrement: db.createObjectStore("items", {autoIncrement:true});

Now I want to be able to update an item given its key and a new value, so I wrote this function:

let updateItem = (key, newData) => {
    let objectStore = db.transaction(["items"], "readwrite").objectStore("items");
    let request = objectStore.get(key);
    request.onsuccess = (e) => {
        let data = e.target.result;
        Object.assign(data, newData);
        let requestUpdate = objectStore.put(data);      
    };
}

However, instead of updating the value, it creates a new item with the new data. I think it makes sense since e.target.result does not contain any information about its key. So how do I update an element in such an object store?


Solution

  • You need to add a key as a second parameter, like objectStore.put(data, key).

    key

    The primary key of the record you want to update (e.g. from IDBCursor.primaryKey). This is only needed for object stores that have an autoIncrement primary key, therefore the key is not in a field on the record object. In such cases, calling put(item) will always insert a new record, because it doesn't know what existing record you might want to modify.

    -- IDBObjectStore.put() - Web APIs | MDN