Use the library indexedDB-promised.
Create a database and stroe:
import idb from ‘idb‘; // Open(db_name, version, cb) var dbPromise = idb.open(‘test-db‘, 1, function (upgradeDb) { var keyValStore = upgradeDb.createObjectStore(‘keyval‘); // create table //put(value, key) keyValStore.put(‘world‘, ‘Hello‘); });
Notice put() function take value frist then key.
Read the key in stroe:
// read "hello" in "keyval" dbPromise.then(function (db) { var tx = db.transaction(‘keyval‘); // Open a transaction var keyValStore = tx.objectStore(‘keyval‘); // read the store return keyValStore.get(‘hello‘); // get value by key }).then(function (val) { console.log(‘The value of "hello" is:‘, val); });
Write value to store:
// set "foo" to be "bar" in "keyval" dbPromise.then(function (db) { var tx = db.transaction(‘keyval‘, ‘readwrite‘); // ready for add key value var keyValStore = tx.objectStore(‘keyval‘); // get the store keyValStore.put(‘bar‘, ‘foo‘); // set the value, notice it may not be success if any step in transaction fail. return tx.complete; // tx.complete is a promise }).then(function () { console.log(‘Added foo:bar to keyval‘); });
时间: 2024-10-22 01:15:37