@@ -181,29 +181,44 @@ export function useStorage<T extends (string | number | boolean | object | null)
181
181
182
182
watch ( keyComputed , ( ) => update ( ) , { flush } )
183
183
184
+ let firstMounted = false
185
+ const onStorageEvent = ( ev : StorageEvent ) : void => {
186
+ if ( initOnMounted && ! firstMounted ) {
187
+ return
188
+ }
189
+
190
+ update ( ev )
191
+ }
192
+ const onStorageCustomEvent = ( ev : CustomEvent < StorageEventLike > ) : void => {
193
+ if ( initOnMounted && ! firstMounted ) {
194
+ return
195
+ }
196
+
197
+ updateFromCustomEvent ( ev )
198
+ }
199
+
200
+ /**
201
+ * The custom event is needed for same-document syncing when using custom
202
+ * storage backends, but it doesn't work across different documents.
203
+ *
204
+ * TODO: Consider implementing a BroadcastChannel-based solution that fixes this.
205
+ */
184
206
if ( window && listenToStorageChanges ) {
185
- tryOnMounted ( ( ) => {
186
- /**
187
- * Attaching event listeners here should be fine since we are in a mounted hook
188
- *
189
- * The custom event is needed for same-document syncing when using custom
190
- * storage backends, but it doesn't work across different documents.
191
- *
192
- * TODO: Consider implementing a BroadcastChannel-based solution that fixes this.
193
- */
194
- if ( storage instanceof Storage )
195
- useEventListener ( window , 'storage' , update , { passive : true } )
196
- else
197
- useEventListener ( window , customStorageEventName , updateFromCustomEvent )
207
+ if ( storage instanceof Storage )
208
+ useEventListener ( window , 'storage' , onStorageEvent , { passive : true } )
209
+ else
210
+ useEventListener ( window , customStorageEventName , onStorageCustomEvent )
211
+ }
198
212
199
- if ( initOnMounted )
200
- update ( )
213
+ if ( initOnMounted ) {
214
+ tryOnMounted ( ( ) => {
215
+ firstMounted = true
216
+ update ( )
201
217
} )
202
218
}
203
-
204
- // avoid reading immediately to avoid hydration mismatch when doing SSR
205
- if ( ! initOnMounted )
219
+ else {
206
220
update ( )
221
+ }
207
222
208
223
function dispatchWriteEvent ( oldValue : string | null , newValue : string | null ) {
209
224
// send custom event to communicate within same page
0 commit comments