Skip to content

Commit

Permalink
Local storage: add setItem & hasItem (#184)
Browse files Browse the repository at this point in the history
  • Loading branch information
alimd authored Feb 3, 2025
2 parents 3e2aea5 + a1b845d commit b93c5af
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion packages/local-storage/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,39 @@ export const localJsonStorage = {
* ```
*/
getItem<T extends Json>(name: string, defaultValue: T, version = 1): T {
if (version > 1) {
this.removeItem(name, version - 1);
}
if (version > 1) {
this.removeItem(name, version - 1);
}
const key = this.key_(name, version);
const value = localStorage.getItem(key);
if (value === null) return defaultValue;
if (value === null) {
localStorage.setItem(key, JSON.stringify(defaultValue));
return defaultValue;
}
const json = parseJson<T>(value);
if (json === null || typeof json !== 'object') return defaultValue;
return json;
},

/**
* Check if an item exists in local storage.
*
* @param name - The name of the item.
* @param version - The version of the item (default: 1).
* @returns True if the item exists, false otherwise.
* @example
* ```typescript
* const exists = localJsonStorage.hasItem('myItem');
* ```
*/
hasItem(name: string, version = 1): boolean {
const key = this.key_(name, version);
return localStorage.getItem(key) !== null;
},

/**
* Set local storage item as JSON.
*
Expand Down

0 comments on commit b93c5af

Please sign in to comment.