From 27bffb1fba9de4c958f4a4b4d31c20e54e579fc0 Mon Sep 17 00:00:00 2001 From: Charles Kornoelje <33156025+charkour@users.noreply.github.com> Date: Fri, 19 Jan 2024 21:17:05 -0800 Subject: [PATCH] docs(persist): add info about `createJSONStorage` helpful function (#2299) * first pass at docs * add jump-to-section --- docs/integrations/persisting-store-data.md | 34 ++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/docs/integrations/persisting-store-data.md b/docs/integrations/persisting-store-data.md index 8c3342a0a0..a9ea4a3f83 100644 --- a/docs/integrations/persisting-store-data.md +++ b/docs/integrations/persisting-store-data.md @@ -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: @@ -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,