简体   繁体   中英

Dexie JS (Indexed DB): Using get( ) in addEventListener returning undefined

I've been working on chrome extention project.

What I am trying to do is store the input value and pull it out when the specific button is pressed.

Below is the part of js code:

import { Dexie } from '../node_modules/dexie/dist/dexie.mjs';
var DBName = 'test';
buttonA.addEventListener('click', () => {
    const inp = document.getElementById("inp");

    const db = new Dexie(DBName);
    db.version(2).stores({
        friend: '++id, name'
    });

    db.friend.add({
        name: inp.value
    })
});

buttonB.addEventListener('click', () => {
    const db = new Dexie(DBName);
    const ch = db.friend;
    console.log("Checking the value in DB: " + ch);
});

When I try it, it stores whatever input to indexed DB after clicking buttonA (confirmed by using Chrome Developer Tool), however when it comes to clicking on buttonB, the log tells that ch is undefined (same for db.friend.name or db.name as well). Because of this, even when I use get() , it returns me an error since I am accessing on undefined variable.

Could someone help figuring out why the program does not access properly to an indexed DB that exists when I click on a buttonB?

Thank you.

Problems:

  1. The second instance of Dexie does not declare which tables there are, so db.friend is unknown.

  2. Your code creates a new Dexie for every click. It would be much better and faster to reuse a single Dexie instance. If you create a new Dexie instance everytime, you must also close it after you to avoid resource leakage.

Recommendation:

Declare a singleton Dexie instance with version().stores(...) so it populates the 'friend' property for you.

Preferably this code could be in it's own module (such as 'db.js').

Use that single Dexie instance from any place where you need to store or read from the db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM