Skip to content

Commit a1b845d

Browse files
committed
feat(local-storage): add setItem after getItem and add hasItem
1 parent 3e2aea5 commit a1b845d

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

packages/local-storage/src/main.ts

+23-1
Original file line numberDiff line numberDiff line change
@@ -60,17 +60,39 @@ export const localJsonStorage = {
6060
* ```
6161
*/
6262
getItem<T extends Json>(name: string, defaultValue: T, version = 1): T {
63+
if (version > 1) {
64+
this.removeItem(name, version - 1);
65+
}
6366
if (version > 1) {
6467
this.removeItem(name, version - 1);
6568
}
6669
const key = this.key_(name, version);
6770
const value = localStorage.getItem(key);
68-
if (value === null) return defaultValue;
71+
if (value === null) {
72+
localStorage.setItem(key, JSON.stringify(defaultValue));
73+
return defaultValue;
74+
}
6975
const json = parseJson<T>(value);
7076
if (json === null || typeof json !== 'object') return defaultValue;
7177
return json;
7278
},
7379

80+
/**
81+
* Check if an item exists in local storage.
82+
*
83+
* @param name - The name of the item.
84+
* @param version - The version of the item (default: 1).
85+
* @returns True if the item exists, false otherwise.
86+
* @example
87+
* ```typescript
88+
* const exists = localJsonStorage.hasItem('myItem');
89+
* ```
90+
*/
91+
hasItem(name: string, version = 1): boolean {
92+
const key = this.key_(name, version);
93+
return localStorage.getItem(key) !== null;
94+
},
95+
7496
/**
7597
* Set local storage item as JSON.
7698
*

0 commit comments

Comments
 (0)