Skip to content

Commit

Permalink
use try-catch
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed May 29, 2024
1 parent 71d2fa0 commit 6ca781f
Showing 1 changed file with 23 additions and 20 deletions.
43 changes: 23 additions & 20 deletions src/vanilla/utils/atomWithStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,34 +161,37 @@ export function createJSONStorage<Value>(
callback(newValue)
})

let subscriber: StringSubscribe | undefined
try {
subscriber = getStringStorage()?.subscribe
} catch {
// ignore
}
if (
!subscriber &&
typeof window !== 'undefined' &&
typeof window.addEventListener === 'function'
typeof window.addEventListener === 'function' &&
window.Storage
) {
let subscriber = getStringStorage()?.subscribe
if (
!subscriber &&
window.Storage &&
getStringStorage() instanceof window.Storage
) {
subscriber = (key, callback) => {
const storageEventCallback = (e: StorageEvent) => {
if (e.storageArea === getStringStorage() && e.key === key) {
callback(e.newValue)
}
}
window.addEventListener('storage', storageEventCallback)
return () => {
window.removeEventListener('storage', storageEventCallback)
subscriber = (key, callback) => {
if (!(getStringStorage() instanceof window.Storage)) {
return () => {}
}
const storageEventCallback = (e: StorageEvent) => {
if (e.storageArea === getStringStorage() && e.key === key) {
callback(e.newValue)
}
}
}

if (subscriber) {
storage.subscribe = createHandleSubscribe(subscriber)
window.addEventListener('storage', storageEventCallback)
return () => {
window.removeEventListener('storage', storageEventCallback)
}
}
}

if (subscriber) {
storage.subscribe = createHandleSubscribe(subscriber)
}
return storage
}

Expand Down

0 comments on commit 6ca781f

Please sign in to comment.