floranet/src/hooks/useLocalStorage.js

67 lines
1.9 KiB
JavaScript

import { LocalStorage, SessionStorage } from "quasar";
export function useLocalStorage() {
/**
* Adds an item to localStorage.
* @param {string} key - The key of the item to be added.
* @param {*} value - The value of the item to be added.
*/
const addItem = (key, value) => {
const stringifyValue = JSON.stringify(value);
LocalStorage.set(`@${key}`, stringifyValue);
};
/**
* Adds an item to SessionStorage.
* @param {string} key - The key of the item to be added.
* @param {*} value - The value of the item to be added.
*/
const addItemSession = (key, value) => {
SessionStorage.set(`@${key}`, stringifyValue);
}
/**
* Retrieves an item from the local storage based on the provided key.
*
* @param {string} key - The key of the item to retrieve.
* @returns {Object|Array} - The retrieved item from the local storage. If the key is "availability", it returns an object, otherwise it returns an array.
*/
const getItem = (key) => {
const data = JSON.parse(LocalStorage.getItem(`@${key}`));
if (key === "availability") return data || {};
return data || [];
};
/**
* Retrieves an item from the local storage based on the provided key.
*
* @param {string} key - The key of the item to retrieve.
* @returns {Object|Array} - The retrieved item from the local storage. If the key is "availability", it returns an object, otherwise it returns an array.
*/
const getItemSession = (key) => {
const data = JSON.parse(SessionStorage.getItem(`@${key}`));
if (key === "availability") return data || {};
return data || [];
};
/**
* Remove an item from local storage.
*
* @param {string} key - The key of the item to remove.
*/
const removeItem = (key) => {
LocalStorage.remove(`@${key}`);
};
return {
addItem,
getItem,
removeItem,
addItemSession,
getItemSession
};
}