Skip to content

Commit

Permalink
docs: update documentation of persist (#2147)
Browse files Browse the repository at this point in the history
* docs: update documentation of persist

Add superjson serialization/deserialization example to Zustand persist documentation

* docs: fix spelling documentation of persist

* docs: Apply feedback by moving content under custom storage engine and specifying that the code is an example

* docs: Update variable name to example name and separate storage as const
  • Loading branch information
cheatkey authored Nov 1, 2023
1 parent e138de7 commit 492637a
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions docs/integrations/persisting-store-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,54 @@ export const useBoundStore = create(
)
```

If you're using a type that JSON.stringify() doesn't support, you'll need to write your own serialization/deserialization code. However, if this is tedious, you can use third-party libraries to serialize and deserialize different types of data.

For example, [Superjson](https://github.com/blitz-js/superjson) can serialize data along with its type, allowing the data to be parsed back to its original type upon deserialization

```ts
import superjson from 'superjson' // can use anything: serialize-javascript, devalue, etc.
import { PersistStorage } from 'zustand/middleware'

interface BearState {
bear: Map<string, string>
fish: Set<string>
time: Date
query: RegExp
}

const storage: PersistStorage<BearState> = {
getItem: (name) => {
const str = localStorage.getItem(name)
if (!str) return null
return superjson.parse(str)
},
setItem: (name, value) => {
localStorage.setItem(name, superjson.stringify(value))
},
removeItem: (name) => localStorage.removeItem(name),
}

const initialState: BearState = {
bear: new Map(),
fish: new Set(),
time: new Date(),
query: new RegExp(''),
}

export const useBearStore = create<BearState>()(
persist(
(set) => ({
...initialState,
// ...
}),
{
name: 'food-storage',
storage,
}
)
)
```

### How can I rehydrate on storage event

You can use the Persist API to create your own implementation,
Expand Down

1 comment on commit 492637a

@vercel
Copy link

@vercel vercel bot commented on 492637a Nov 1, 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.