3

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?

1
  • @Josh yup.. It is a duplicate.. Sorry, I tried my best to search before asking.. Thank you for your comment.
    – wololoo
    Commented Oct 30, 2020 at 22:39

2 Answers 2

3

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

1
  • I found another solution but yours also solves the problem so I'm accepting it. Thanks!
    – wololoo
    Commented Oct 30, 2020 at 22:40
0

I found another solution using cursor.update():

let updateItem = (key, newData) => {
    let objectStore = db.transaction("items","readwrite").objectStore("items");
    objectStore.openCursor().onsuccess = (e) => {
        let cursor = e.target.result;
        if (cursor && cursor.key == key) {
            cursor.update(Object.assign(cursor.value, newData));
            cursor.continue();
        }
    };
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.