Javascript
utils
Localstorate Util

Local Storage Utils With Parsing of Values and Errors

Since you are obliged to strinfigy and parse to use localStorage with objects, this micro labray will help you

Usage

import { storage } from "../utils/storage";

storage.setItem("favourites", updateFavourites); add item at key storage.getItem("favourites"); get item by key storage.removetItem("favourites"); remove item in key storage.clearStorage(); empty the storage, removing all keys

export const storage = {
    setItem: (key: string, value: any) => { // add item at key
        try {
          const serializedValue = typeof value !== "string" ? JSON.stringify(value) : value; // try to stringify if object was passed
          localStorage.setItem(key, serializedValue);
        } catch (error) {
          console.error(`Error setting item ${key} in localStorage`, error);
        }
    },
 
    getItem: (key: string) => { // get item by key
        try {
          const serializedValue = localStorage.getItem(key);
          return serializedValue ? JSON.parse(serializedValue) : null; // Has value parse, any invalid value return null;
        } catch (error) {
          console.error(`Error getting item ${key} from localStorage`, error);
          return null;
        }
    },
 
    removeItem: (key: string) => { // remove item in key
        try {
          localStorage.removeItem(key);
        } catch (error) {
          console.error(`Error removing item ${key} from localStorage`, error);
        }
    },
 
    clearStorage: () => { // empty the storage, removing all keys
        try {
          localStorage.clear();
        } catch (error) {
          console.error('Error clearing localStorage', error);
        }
    }
      
}
 
Last updated on