How do I save an object in IndexedDB?

toe95027  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(203)

我想把我的API数据存储在Browser的indexedDB中。我想尝试本地存储,但它有5MB的限制,但我的JSON数据超过7MB。我想保存在indexedDB中,以便更快地访问。我想以JSON格式保存整个数据,但不知道如何设置 IndexedDB 的方案。从数据库中取出的数据是testData

const db =new Dexie("ReactDexie");
db.version(1).stores({
            test:"++id title "   //Dont Know how to set scheme here for my json object
        })
        db.open().catch((err)=>{
            console.log(err.stack || err)
        })

        var transaction = db.transaction([testData], IDBTransaction.READ_WRITE); 
        var objstore = transaction.objectStore(testData); 

        for (var i = 0; i < testData.length; i++) { 
            objstore.put(testData[i]);
        }
vyu0f0g1

vyu0f0g11#

Follow these steps for good architecture and reusable components ( Sample project is created here ):-
1 ) Create one file lets just name it indexDB.js

import Dexie from 'dexie';

const db = new Dexie('ReactDexie');

db.version(1).stores({
  testData: 'datakey'
});

export default db;

2 ) Now make one utility function that will store API data (let's assume this is in file utility.js )

import db from './indexDB.js';

export async function saveDataInIndexDB(data) {
  if (data) {
    if (db.testData) db.testData.clear();
    db.testData.add({ datakey: 'datakey', data }).then(() => {});
  }
}

3 ) function for fetching data from indexDB (in utility.js file)

export async function getDataFromIndexDB() {
  const testData = await db.testData
    .where('datakey')
    .equals('datakey')
    .toArray();
  if (testData && testData.length > 0) {
    return testData[0];
  }
  return null;
}

4 ) I am considering sample JSON data as following (suppose you are getting this data in App.js )

const sampleJSONdata = {
    type: 'articles',
    id: '1',
    attributes: {
      title: 'JSON:API paints my bikeshed!',
      body: 'The shortest article. Ever.',
      created: '2015-05-22T14:56:29.000Z',
      updated: '2015-05-22T14:56:28.000Z'
    }
  };

5 ) Store and Fetch data as following (you can call utility.js functions in `App.js file)

saveDataInIndexDB(sampleJSONdata);

  const getDataFromDB = async () => {
    let data = await getDataFromIndexDB();
    console.log('Data ', data);
  };

  console.log(getDataFromDB());

The sample project is created here , you can refer to this project for further use, more about schema and useful Dexie related article you can find here .
Note*- Please clear site data, you might face multiple version issues as you were trying earlier (in that case you can change or add extraversion)

相关问题