Vue.js useStorage composable
Simple yet very handy Vue.js composable to interact with the JavaScript localStorage API.
import { reactive } from "vue";
const storage = reactive({});
const storageType = localStorage;
/**
* @param key
* @returns {boolean}
*/
function storageInit(key) {
if(typeof key !== 'string') return false; // invalid
if(storage.hasOwnProperty(key)) return; // exists
storage[key] = storageType.getItem(key) ? storageGet(key) : [];
}
/**
* @param key
* @returns {any}
*/
function storageGet(key) {
if(!storageType.getItem(key)) return;
return JSON.parse(storageType.getItem(key));
}
/**
* @param key
* @returns {boolean}
*/
function storageSet(key) {
if(typeof key !== 'string') return false; // invalid
storageType.setItem(key, JSON.stringify(storage[key]));
}
/**
* @param key
* @param item
*/
function storageAdd(key, item){
if(storageInit(key) === false) return;
if(!storage[key].includes(item)) {
storage[key].push(item);
storageSet(key);
}
}
/**
* @param key
* @param item
* @returns {boolean}
*/
function storageHas(key, item){
if(storageInit(key) === false) return;
return storage.hasOwnProperty(key) && JSON.parse(JSON.stringify(storage[key]))?.includes(item);
}
export default function useStorage() {
return {
storageAdd,
storageHas,
storage
}
}