Skip to content

Commit

Permalink
✨ new storeDefault option #1
Browse files Browse the repository at this point in the history
  • Loading branch information
astoilkov committed Aug 7, 2024
1 parent b963d09 commit e666bcb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
8 changes: 8 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,14 @@ Default: `true`

Setting to `false` doesn't subscribe to the [Window storage event](https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event). If you set to `false`, updates won't be synchronized across tabs, windows and iframes.

#### `options.storeDefault`

Type: `boolean`

Default: `false`

Setting to `true` calls `storage.setItem()` for the default value so the default value is persisted in `Storage` after the first render of the hook.

#### `options.serializer`

Type: `{ stringify, parse }`
Expand Down
5 changes: 4 additions & 1 deletion src/useStorageState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export type StorageStateOptions<T> = {
defaultValue?: T | (() => T)
storage?: Storage
sync?: boolean
storeDefault?: boolean
serializer?: {
stringify: (value: unknown) => string
parse: (value: string) => unknown
Expand Down Expand Up @@ -42,6 +43,7 @@ export default function useStorageState<T = undefined>(
defaultValue,
options?.storage,
options?.sync,
options?.storeDefault,
serializer?.parse,
serializer?.stringify,
)
Expand All @@ -52,6 +54,7 @@ function useStorage<T>(
defaultValue: T | undefined,
storage: Storage = goodTry(() => localStorage) ?? sessionStorage,
sync: boolean = true,
storeDefault: boolean = false,
parse: (value: string) => unknown = parseJSON,
stringify: (value: unknown) => string = JSON.stringify,
): StorageState<T | undefined> {
Expand Down Expand Up @@ -101,7 +104,7 @@ function useStorage<T>(
// 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 (defaultValue !== undefined && string === null) {
if (storeDefault && defaultValue !== undefined && string === null) {
// reasons for `localStorage` to throw an error:
// - maximum quota is exceeded
// - under Mobile Safari (since iOS 5) when the user enters private mode
Expand Down

0 comments on commit e666bcb

Please sign in to comment.