File tree Expand file tree Collapse file tree 2 files changed +35
-15
lines changed Expand file tree Collapse file tree 2 files changed +35
-15
lines changed Original file line number Diff line number Diff line change @@ -464,6 +464,21 @@ describe('useStorage', () => {
464
464
expect ( call [ 0 ] . detail . key ) . toEqual ( KEY )
465
465
expect ( call [ 0 ] . detail . oldValue ) . toEqual ( '0' )
466
466
expect ( call [ 0 ] . detail . newValue ) . toEqual ( '1' )
467
+
468
+ window . addEventListener ( customStorageEventName , eventFn , { once : true } )
469
+
470
+ data0 . value = null
471
+ await nextTwoTick ( )
472
+
473
+ expect ( data0 . value ) . toBe ( 0 )
474
+ expect ( data1 . value ) . toBe ( 0 )
475
+ expect ( eventFn ) . toHaveBeenCalledTimes ( 2 )
476
+ const call2 = eventFn . mock . calls [ 1 ] as [ CustomEvent ]
477
+
478
+ expect ( call2 [ 0 ] . detail . storageArea ) . toEqual ( storage )
479
+ expect ( call2 [ 0 ] . detail . key ) . toEqual ( KEY )
480
+ expect ( call2 [ 0 ] . detail . oldValue ) . toEqual ( '1' )
481
+ expect ( call2 [ 0 ] . detail . newValue ) . toEqual ( null )
467
482
} )
468
483
469
484
it ( 'handle error' , ( ) => {
Original file line number Diff line number Diff line change @@ -195,28 +195,33 @@ export function useStorage<T extends(string | number | boolean | object | null)>
195
195
196
196
function write ( v : unknown ) {
197
197
try {
198
+ const oldValue = storage ! . getItem ( key )
199
+
200
+ const dispatchWriteEvent = ( newValue : string | null ) => {
201
+ // send custom event to communicate within same page
202
+ // importantly this should _not_ be a StorageEvent since those cannot
203
+ // be constructed with a non-built-in storage area
204
+ if ( window ) {
205
+ window . dispatchEvent ( new CustomEvent < StorageEventLike > ( customStorageEventName , {
206
+ detail : {
207
+ key,
208
+ oldValue,
209
+ newValue,
210
+ storageArea : storage ! ,
211
+ } ,
212
+ } ) )
213
+ }
214
+ }
215
+
198
216
if ( v == null ) {
217
+ dispatchWriteEvent ( null )
199
218
storage ! . removeItem ( key )
200
219
}
201
220
else {
202
221
const serialized = serializer . write ( v as any )
203
- const oldValue = storage ! . getItem ( key )
204
222
if ( oldValue !== serialized ) {
205
223
storage ! . setItem ( key , serialized )
206
-
207
- // send custom event to communicate within same page
208
- // importantly this should _not_ be a StorageEvent since those cannot
209
- // be constructed with a non-built-in storage area
210
- if ( window ) {
211
- window . dispatchEvent ( new CustomEvent < StorageEventLike > ( customStorageEventName , {
212
- detail : {
213
- key,
214
- oldValue,
215
- newValue : serialized ,
216
- storageArea : storage ! ,
217
- } ,
218
- } ) )
219
- }
224
+ dispatchWriteEvent ( serialized )
220
225
}
221
226
}
222
227
}
You can’t perform that action at this time.
0 commit comments