Skip to content

Commit

Permalink
♻️ move logic inside of useSyncExternalStore.getSnapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
astoilkov committed Apr 22, 2024
1 parent 010a16e commit 247cc27
Showing 1 changed file with 20 additions and 24 deletions.
44 changes: 20 additions & 24 deletions src/useLocalStorageState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,30 +83,6 @@ function useBrowserLocalStorageState<T>(
parsed: undefined,
})

// store default value in localStorage:
// - initial issue: https://github.com/astoilkov/use-local-storage-state/issues/26
// issues that were caused by incorrect initial and secondary implementations:
// - https://github.com/astoilkov/use-local-storage-state/issues/30
// - https://github.com/astoilkov/use-local-storage-state/issues/33
if (
!inMemoryData.has(key) &&
defaultValue !== undefined &&
goodTry(() => localStorage.getItem(key)) === null
) {
// reasons for `localStorage` to throw an error:
// - maximum quota is exceeded
// - under Mobile Safari (since iOS 5) when the user enters private mode
// `localStorage.setItem()` will throw
// - trying to access localStorage object when cookies are disabled in Safari throws
// "SecurityError: The operation is insecure."
// eslint-disable-next-line no-console
goodTry(() => {
const string = stringify(defaultValue)
localStorage.setItem(key, string)
storageItem.current = { string, parsed: defaultValue }
})
}

const value = useSyncExternalStore(
useCallback(
(onStoreChange) => {
Expand Down Expand Up @@ -143,6 +119,26 @@ function useBrowserLocalStorageState<T>(

storageItem.current.string = string

// store default value in localStorage:
// - initial issue: https://github.com/astoilkov/use-local-storage-state/issues/26
// issues that were caused by incorrect initial and secondary implementations:
// - https://github.com/astoilkov/use-local-storage-state/issues/30
// - https://github.com/astoilkov/use-local-storage-state/issues/33
if (string === null && defaultValue !== undefined) {
// reasons for `localStorage` to throw an error:
// - maximum quota is exceeded
// - under Mobile Safari (since iOS 5) when the user enters private mode
// `localStorage.setItem()` will throw
// - trying to access localStorage object when cookies are disabled in Safari throws
// "SecurityError: The operation is insecure."
// eslint-disable-next-line no-console
goodTry(() => {
const string = stringify(defaultValue)
localStorage.setItem(key, string)
storageItem.current = { string, parsed: defaultValue }
})
}

return storageItem.current.parsed
},

Expand Down

0 comments on commit 247cc27

Please sign in to comment.