DEV Community

Andrés Valdivia Cuzcano
Andrés Valdivia Cuzcano

Posted on

Update data from IndexedDB

To update an existing data in the database, the put(item, key) method is used. However, if the requested data doesn't exist, this method creates it and inserts it in the Object Store. This method returns the key of the stored object as a result.

The method used has two parameters, the first is the object to update or insert, and the second parameter is optional and refers to the key of the object, this last parameter is only necessary when an autoincrement value is used as the key of the stored objects, since if it is not specified a new object will be created with an automatically generated key.

To update, usually the get(key) method is first used to get the stored object, then the necessary properties are updated, and finally the put(obj) method is used with the new object.

function updateStudent(key){
    const objectStore = db.transaction('students')

    const request = objectStore.get(key);

    request.onsuccess = ()=> {

        const student = request.result;

        // Change the name property = 'Fulanito';

        // Create a request to update
        const updateRequest = objectStore.update(student);

        updateRequest.onsuccess = () => {

            console.log(`Estudent updated, email: ${updateRequest.result}`)


Enter fullscreen mode Exit fullscreen mode

Top comments (1)

jezmck profile image
Info Comment hidden by post author - thread only accessible via permalink
Jez McKean

I'm puzzled. You say

To update an existing data in the database, the put(item, key) method is used.

Some comments have been hidden by the post's author - find out more