jakearchibald / idb-keyval

A super-simple-small promise-based keyval store implemented with IndexedDB

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Once you have created a database how do you open it from another page?

delebash opened this issue · comments

Example

Page 1

import {createStore, get, set} from 'idb-keyval'
const db = createStore('test', 'user-settings');

Page 2
import {createStore, get, set} from 'idb-keyval'
I know I can just put const db = createStore('test', 'user-settings'); and it works but I thought maybe there was a better way of doing it with open or something like that

Page 1:

import { set, createStore } from 'idb-keyval';
const customStore = createStore('test', 'user-settings');

set('hello', 'world', customStore);

Page 2:

import { set, createStore } from 'idb-keyval';
const customStore = createStore('test', 'user-settings');

get('hello', customStore).then((val) => console.log(val));

If you're doing frequent work with other stores, you might find things easier with https://www.npmjs.com/package/idb:

my-db.js:

import { openDB } from 'idb';

export const open = () => openDB('test', 1, {
  upgrade(db) {
    db.createObjectStore('user-settings');
  },
});

Page 1:

import { open } from './my-db.js';

open().then(async (db) => {
  db.put('user-settings', 'world', 'hello');
});

Page 2:

import { open } from './my-db.js';

open().then(async (db) => {
  console.log(await db.get('user-settings', 'hello'));
});

Thanks for the info and making this module. Cheers!