Skip to content

Commit

Permalink
feat(util): setLocalStorageItem
Browse files Browse the repository at this point in the history
  • Loading branch information
AliMD authored and njfamirm committed Apr 27, 2023
1 parent f386198 commit 46e248c
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions core/util/src/local-storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,14 @@ import {parseJson} from './json.js';
import type {Stringifyable} from '@alwatr/type';

export const getLocalStorageItem = <T extends Stringifyable>(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 = <T extends Stringifyable>(name: string, value: T): void => {
if (value == null) {
localStorage.removeItem(name);
}
localStorage.setItem(name, JSON.stringify(value));
};

0 comments on commit 46e248c

Please sign in to comment.