UNPKG

vue-hooks-plus

Version:
72 lines (71 loc) 2.13 kB
import { ref, watchEffect, readonly, unref } from "vue"; function isFunction(obj) { return typeof obj === "function"; } function createUseStorageState(getStorage) { function useStorageState(key, options) { let storage; try { storage = getStorage(); } catch (err) { console.error(err); } const serializer = (value) => { if (options == null ? void 0 : options.serializer) { return options == null ? void 0 : options.serializer(value); } return JSON.stringify(value); }; const deserializer = (value) => { if (options == null ? void 0 : options.deserializer) { return options == null ? void 0 : options.deserializer(value); } return JSON.parse(value); }; function getStoredValue() { try { const raw = storage == null ? void 0 : storage.getItem(unref(key)); if (raw) { return deserializer(raw); } } catch (e) { console.error(e); } if (isFunction(options == null ? void 0 : options.defaultValue)) { return options == null ? void 0 : options.defaultValue(); } return options == null ? void 0 : options.defaultValue; } const state = ref(getStoredValue()); watchEffect(() => { if (key) state.value = getStoredValue(); }); const updateState = (value) => { if (typeof value === "undefined") { state.value = void 0; storage == null ? void 0 : storage.removeItem(unref(key)); } else if (isFunction(value)) { const currentState = value(state.value); try { state.value = currentState; storage == null ? void 0 : storage.setItem(unref(key), serializer(currentState)); } catch (e) { console.error(e); } } else { try { state.value = value; storage == null ? void 0 : storage.setItem(unref(key), serializer(value)); } catch (e) { console.error(e); } } }; return [readonly(state), updateState]; } return useStorageState; } export { createUseStorageState };