[PWA] 12. Intro to IndexedDB
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PWA] 12. Intro to IndexedDB相关的知识,希望对你有一定的参考价值。
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\'); });
以上是关于[PWA] 12. Intro to IndexedDB的主要内容,如果未能解决你的问题,请参考以下文章
[PWA] Add Push Notifications to a PWA with React in Chrome and on Android
[PWA] Add web app to your Home Screen