Skip to content

Commit

Permalink
refactor 2
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed May 24, 2024
1 parent 1044dfa commit 38bb47e
Showing 1 changed file with 19 additions and 18 deletions.
37 changes: 19 additions & 18 deletions src/vanilla/utils/atomWithStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,25 +161,26 @@ export function createJSONStorage<Value>(
callback(newValue)
})

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

if (subscriber) {
storage.subscribe = createHandleSubscribe(subscriber)
Expand Down

0 comments on commit 38bb47e

Please sign in to comment.