Reputation: 119
I want to store my API data in indexedDB of Browser. I would have tried local storage but it has a limit of 5MB but my JSON data is more than 7MB. I want to save in indexedDB for faster access. I want to save the whole data in the JSON format but don't know how to set the scheme of the indexed DB. The data fetched from the database is 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]);
}
Upvotes: 3
Views: 6358
Reputation: 891
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)
Upvotes: 7