0

I'm trying to Store some application data using indexedDB

Here is my code

function _getLocalApplicationCache(_, payload) {
const indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.shimIndexedDB;
if (!indexedDB) {
    if (__DEV__) {
        console.error("IndexedDB could not found in this browser.");
    }
}

const request = indexedDB.open("ApplicationCache", 1);
request.onerror = event => {
    if (__DEV__) {
        console.error("An error occurred with IndexedDB.");
        console.error(event);
    }
    return;
};

request.onupgradeneeded = function () {
    const db = request.result;
    const store = db.createObjectStore("swimlane", {keyPath: "id", autoIncrement: true});
    store.createIndex("keyData", ["name"], {unique: false});
};

request.onsuccess = () => {
    // creating the transition
    const db = request.result;
    const transition = db.transaction("swimlane", "readwrite");

    // Reference to our object store that holds the swimlane data;
    const store = transition.objectStore("swimlane");
    const swimlaneData = store.index("keyData");

    payload = JSON.parse(JSON.stringify(payload));
    store.put(payload);

    const Query = swimlaneData.getAll(["keyData"]);

    Query.onsuccess = () => {
        if (__DEV__) {
            console.log("Application Cache is loaded", Query.result);
        }
    };
    transition.oncomplete = () => {
        db.close();
    };
};

}

If I do use different version then 1 here --> indexedDB.open("ApplicationCache", 1); I'm getting a error like they keyPath is already exist. And other than than for version 1 I'm getting this error.

Can someone please help me where i'm doing wrong.

1 Answers1

0
  • Review the introductory materials on using indexedDB.
  • If you did something like connect and create a database without a schema, or created an object store without an explicit key path, and then you stored some objects, and then you edited the upgradeneeded callback to specify the keypath, and then never triggered the upgradeneeded callback to run because you continue to use current version number instead of a newer version number, it would be one possible explanation for this error.
  • The upgradeneeded callback needs to have logic that checks for whether the object stores and indices already exist, and only create them if they do not exist. If the store does not exist, create it and its indices. If the store exists and the indices do not, add indices to the store. If the store exists and the indices exist, do nothing.
  • You need to trigger the upgradeneeded callback to run after changing your database schema by connecting with a higher version number. If you do not connect with a higher version number, the callback never runs, so you will end up connecting to the older version where your schema changes have not taken place.
Josh
  • 17,834
  • 7
  • 50
  • 68