Skip to content

Commit

Permalink
feat(utils): getOnInit option for atomWithStorage (#2246)
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi authored Nov 25, 2023
1 parent de67e40 commit f57bbec
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
4 changes: 4 additions & 0 deletions docs/utilities/storage.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ The `atomWithStorage` function creates an atom with a value persisted in `localS
- **removeItem(key)** (required): Deletes the item from storage
- **subscribe(key, callback, initialValue)** (optional): A method which subscribes to external storage updates.

**options** (optional): an object with the following properties:

- **getOnInit** (optional): A boolean value indicating whether to get item from storage on initialization.

If not specified, the default storage implementation uses `localStorage` for storage/retrieval, `JSON.stringify()`/`JSON.parse()` for serialization/deserialization, and subscribes to `storage` events for cross-tab synchronization.

<CodeSandbox id="vuwi7" />
Expand Down
8 changes: 4 additions & 4 deletions src/vanilla/utils/atomWithStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ export function atomWithStorage<Value>(
key: string,
initialValue: Value,
storage: AsyncStorage<Value>,
unstable_options?: { unstable_getOnInit?: boolean },
options?: { getOnInit?: boolean },
): WritableAtom<
Value | Promise<Value>,
[SetStateActionWithReset<Value | Promise<Value>>],
Expand All @@ -133,7 +133,7 @@ export function atomWithStorage<Value>(
key: string,
initialValue: Value,
storage?: SyncStorage<Value>,
unstable_options?: { unstable_getOnInit?: boolean },
options?: { getOnInit?: boolean },
): WritableAtom<Value, [SetStateActionWithReset<Value>], void>

export function atomWithStorage<Value>(
Expand All @@ -142,9 +142,9 @@ export function atomWithStorage<Value>(
storage:
| SyncStorage<Value>
| AsyncStorage<Value> = defaultStorage as SyncStorage<Value>,
unstable_options?: { unstable_getOnInit?: boolean },
options?: { getOnInit?: boolean },
): any {
const getOnInit = unstable_options?.unstable_getOnInit
const getOnInit = options?.getOnInit
const baseAtom = atom(
getOnInit
? (storage.getItem(key, initialValue) as Value | Promise<Value>)
Expand Down

1 comment on commit f57bbec

@vercel
Copy link

@vercel vercel bot commented on f57bbec Nov 25, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.