From 46e248cb79b7846f568eadc5a6d5a2214fe4faf3 Mon Sep 17 00:00:00 2001 From: Ali Mihandoost Date: Thu, 27 Apr 2023 15:57:51 +0330 Subject: [PATCH] feat(util): setLocalStorageItem --- core/util/src/local-storage.ts | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/util/src/local-storage.ts b/core/util/src/local-storage.ts index c7d73872a..d1c21eabb 100644 --- a/core/util/src/local-storage.ts +++ b/core/util/src/local-storage.ts @@ -3,6 +3,14 @@ import {parseJson} from './json.js'; import type {Stringifyable} from '@alwatr/type'; export const getLocalStorageItem = (name: string, defaultValue: T): T => { - const item = localStorage.getItem(name); - return item == null ? defaultValue : parseJson(item) ?? defaultValue; + const value = localStorage.getItem(name); + if (value === 'null' || value === 'undefined') return defaultValue; + return value == null ? defaultValue : parseJson(value) ?? defaultValue; +}; + +export const setLocalStorageItem = (name: string, value: T): void => { + if (value == null) { + localStorage.removeItem(name); + } + localStorage.setItem(name, JSON.stringify(value)); };