Skip to content

Commit 27bffb1

Browse files
authored
docs(persist): add info about createJSONStorage helpful function (#2299)
* first pass at docs * add jump-to-section
1 parent 13830c1 commit 27bffb1

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

docs/integrations/persisting-store-data.md

+32-2
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,7 @@ import { StateStorage } from 'zustand/middleware'
5656

5757
> Default: `createJSONStorage(() => localStorage)`
5858
59-
Enables you to use your own storage.
60-
Simply pass a function that returns the storage you want to use.
59+
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.
6160

6261
Example:
6362

@@ -415,6 +414,37 @@ const unsub = useBoundStore.persist.onFinishHydration((state) => {
415414
unsub()
416415
```
417416

417+
### `createJSONStorage`
418+
419+
> Type: `(getStorage: () => StateStorage, options?: JsonStorageOptions) => StateStorage`
420+
421+
> Returns: `PersistStorage`
422+
423+
This helper function enables you to create a [`storage`](#storage) object which is useful when you want to use a custom storage engine.
424+
425+
`getStorage` is a function that returns the storage engine with the properties `getItem`, `setItem`, and `removeItem`.
426+
427+
`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.
428+
429+
```ts
430+
import { createJSONStorage } from 'zustand/middleware'
431+
432+
const storage = createJSONStorage(() => sessionStorage, {
433+
reviver: (key, value) => {
434+
if (value && value.type === 'date') {
435+
return new Date(value)
436+
}
437+
return value
438+
},
439+
replacer: (key, value) => {
440+
if (value instanceof Date) {
441+
return { type: 'date', value: value.toISOString() }
442+
}
443+
return value
444+
},
445+
})
446+
```
447+
418448
## Hydration and asynchronous storages
419449

420450
To explain what is the "cost" of asynchronous storages,

0 commit comments

Comments
 (0)