Commit a1b845d 1 parent 3e2aea5 commit a1b845d Copy full SHA for a1b845d
File tree 1 file changed +23
-1
lines changed
packages/local-storage/src
1 file changed +23
-1
lines changed Original file line number Diff line number Diff line change @@ -60,17 +60,39 @@ export const localJsonStorage = {
60
60
* ```
61
61
*/
62
62
getItem < T extends Json > ( name : string , defaultValue : T , version = 1 ) : T {
63
+ if ( version > 1 ) {
64
+ this . removeItem ( name , version - 1 ) ;
65
+ }
63
66
if ( version > 1 ) {
64
67
this . removeItem ( name , version - 1 ) ;
65
68
}
66
69
const key = this . key_ ( name , version ) ;
67
70
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
+ }
69
75
const json = parseJson < T > ( value ) ;
70
76
if ( json === null || typeof json !== 'object' ) return defaultValue ;
71
77
return json ;
72
78
} ,
73
79
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
+
74
96
/**
75
97
* Set local storage item as JSON.
76
98
*
You can’t perform that action at this time.
0 commit comments