@vue-material/core
Version:
Yet another 'Material Design Components' library for Vue3.
43 lines (42 loc) • 1.34 kB
JavaScript
import { IDBStorage } from "../utils/idb/index.js";
import { ref, onMounted, onUnmounted, watch, toRaw } from "vue";
function useIDBStorage(key, defaultValue) {
let ignore = true;
const ready = ref(false);
const index = ref(defaultValue);
const state = Object.assign(index, { ready });
async function itemUpdate(data) {
if (data.key === key) {
const data2 = await IDBStorage.hasItem(key) ? await IDBStorage.getItem(key) : defaultValue;
ignore = true;
index.value = data2;
}
}
async function storeCleared() {
index.value = defaultValue;
}
function watcher(data) {
if (ignore) ignore = false;
else IDBStorage.setItem(key, toRaw(data));
}
onMounted(async () => {
var _a;
if (await IDBStorage.hasItem(key)) {
const data = await IDBStorage.getItem(key);
index.value = data;
}
ready.value = true;
(_a = state.onload) == null ? void 0 : _a.call(state, index.value);
IDBStorage.addEventListener("storage", itemUpdate);
IDBStorage.addEventListener("store-cleared", storeCleared);
});
onUnmounted(() => {
IDBStorage.removeEventListener("storage", itemUpdate);
IDBStorage.removeEventListener("store-cleared", storeCleared);
});
watch(index, watcher, { deep: true });
return Object.assign(index, { ready });
}
export {
useIDBStorage
};