简体   繁体   中英

Push value in Array in IndexedDB

I want to push values in an Array in IndexedDB. But it seems like the put() method replaces / overrides the existing data.

 const idbPromise = async() => { try { const db = await openDB("first", 1, { // dbx, oldVersion, newVersion, transaction upgrade(dbx) { if (!dbx.objectStoreNames.contains(storeName)) { dbx.createObjectStore("data", { keyPath: "name" }); } } }); return db; } catch (error) { return error; } }; const appendData = async(value) => { return idbPromise() .then(function(db) { const tx = db.transaction("data", "readwrite"); const store = tx.objectStore("data"); store.put(data); return tx.complete; }) .catch(e => console.log(e)); } // first call appendData({ name: "arr", value: [1] }); // second call appendData({ name: "arr", value: [2] }); 

The output of the code above is value: [2] but I want to achieve value: [1,2] .
How would I achieve this?

PS: I don't want to copy and the existing values and add all of it, I want it to work like JavaScript's push() method.

As Josh suggested only way to do append is to read the object and then update it - here is a sample written with pure js as I don't have the openDb script which you are using.

 const appendData = (newValue) => { return new Promise(function(resolve, reject){ const request = indexedDB.open("todos"); request.onsuccess = (e) => { const db = e.target.result; const trans = db.transaction(["data"],"readwrite"); const store = trans.objectStore("data"); const openCursorReq = store.openCursor(IDBKeyRange.only(newValue.name)); openCursorReq.onsuccess = (event) => { const cursor = event.target.result; let oldValue = cursor.value; oldValue.value = oldValue.value.concat(newValue.value); var updateRequest = cursor.update(oldValue); updateRequest.onerror = updateRequest.onblocked = () => { console.log('Error updating'); reject(); }; updateRequest.onsuccess = function (event) { console.log('update', newValue); resolve(); }; trans.oncomplete = function(e) { db.close(); }; } }; request.onerror = reject; }) }; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM