Skip to content

Commit

Permalink
docs(persist): add info about createJSONStorage helpful function (#…
Browse files Browse the repository at this point in the history
…2299)

* first pass at docs

* add jump-to-section
  • Loading branch information
charkour authored Jan 20, 2024
1 parent 13830c1 commit 27bffb1
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions docs/integrations/persisting-store-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ import { StateStorage } from 'zustand/middleware'

> Default: `createJSONStorage(() => localStorage)`
Enables you to use your own storage.
Simply pass a function that returns the storage you want to use.
Enables you to use your own storage. Simply pass a function that returns the storage you want to use. It's recommended to use the [`createJSONStorage`](#createjsonstorage) helper function to create a `storage` object that is compliant with the `StateStorage` interface.

Example:

Expand Down Expand Up @@ -415,6 +414,37 @@ const unsub = useBoundStore.persist.onFinishHydration((state) => {
unsub()
```

### `createJSONStorage`

> Type: `(getStorage: () => StateStorage, options?: JsonStorageOptions) => StateStorage`
> Returns: `PersistStorage`
This helper function enables you to create a [`storage`](#storage) object which is useful when you want to use a custom storage engine.

`getStorage` is a function that returns the storage engine with the properties `getItem`, `setItem`, and `removeItem`.

`options` is an optional object that can be used to customize the serialization and deserialization of the data. `options.reviver` is a function that is passed to `JSON.parse` to deserialize the data. `options.replacer` is a function that is passed to `JSON.stringify` to serialize the data.

```ts
import { createJSONStorage } from 'zustand/middleware'

const storage = createJSONStorage(() => sessionStorage, {
reviver: (key, value) => {
if (value && value.type === 'date') {
return new Date(value)
}
return value
},
replacer: (key, value) => {
if (value instanceof Date) {
return { type: 'date', value: value.toISOString() }
}
return value
},
})
```

## Hydration and asynchronous storages

To explain what is the "cost" of asynchronous storages,
Expand Down

1 comment on commit 27bffb1

@vercel
Copy link

@vercel vercel bot commented on 27bffb1 Jan 20, 2024

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.