I have written a localstorage helper for my react application to make it reusable which doesnt feel very reusable. If I save or remove an item, it depends on the storage data type: If its array, I iterate through it, if its an Object or String, I cannot do the same. So Now I have separate functions (saveItemToArray, saveItemToObject etc). I tried also to write a generale function where I check the data type and based on that perform different actions but that also didnt seem practical. Is there a good solution? Thanks a lot!
export const localStorageHelper = {
load: (key) => {
return JSON.parse(localStorage.getItem(key))
},
saveToArr: (item, storageID) => {
let storage = localStorageHelper.load(storageID);
if (!storage) storage = [];
localStorage.setItem(storageID, JSON.stringify([...storage, item]))
},
saveItemToObject: (item, storageID) => {
let storage = localStorageHelper.load(storageID);
if (!storage) storage = {};
localStorage.setItem(storageID, {...storage, item});
},
removeItemFromArray: (removedItem, storageID) => {
let storage = localStorageHelper.load(storageID);
let updatedStorage = storage.filter((item)=> item !==removedItem);
localStorage.setItem(storageID, JSON.stringify(updatedStorage))
},
//...
};