svelte-idb-store
Version:
A library that allows you to sync the value of your Svelte stores with IndexedDB
60 lines (59 loc) • 1.68 kB
JavaScript
import { IDBArray, IDBObject, exists, remove } from "./idb";
export const idbStoreArray = ({ name, key, initialValue = [], onLoad, onCreate }) => {
let s = $state(initialValue);
const idb = new IDBArray(name, key, initialValue, async (creating) => {
s = await idb.get();
if (creating && onCreate) {
onCreate();
}
onLoad && onLoad();
});
return {
get value() {
return s;
},
set value(val) {
idb.set(val).then(res => (s = res));
},
getItem: idb.getItem,
setItem: async (val) => {
s = await idb.setItem(val);
},
removeItem: async (id) => {
s = await idb.removeItem(id);
},
clear: async () => {
s = await idb.clear();
}
};
};
export const idbStoreObject = ({ name, initialValue, onLoad, onCreate }) => {
const idb = new IDBObject(name, undefined, initialValue, async (creating) => {
s = await idb.get();
if (creating && onCreate) {
onCreate();
}
onLoad && onLoad();
});
let s = $state(initialValue);
return {
get value() {
return s || {};
},
set value(val) {
idb.set(val).then(res => (s = res));
},
getItem: idb.getItem,
setItem: async (id, val) => {
s = await idb.setItem(id, val);
},
removeItem: async (id) => {
s = await idb.removeItem(id);
},
clear: async () => {
s = await idb.clear();
}
};
};
export const existsDB = exists;
export const deleteDB = remove;