-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
docs: update documentation of persist #2147
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 3 commits
8fdfe3a
0bb6035
84f202d
eb37b28
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -630,6 +630,37 @@ 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 { StorageValue } from "zustand/middleware"; | ||
|
||
interface BearState { | ||
...: Map<string, string>; | ||
...: Set<string>; | ||
...: Date, | ||
...: RegExp; | ||
} | ||
//... | ||
|
||
storage: { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Wrap it with |
||
getItem: (name) => { | ||
const str = localStorage.getItem(name); | ||
if (!str) return null; | ||
return { | ||
state: superjson.parse<StorageValue<BearState>>(str).state, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm wondering if you need to return There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You don't need to wrap it in an object. The result of |
||
}; | ||
}, | ||
setItem: (name, value) => { | ||
localStorage.setItem(name, superjson.stringify(value)); | ||
}, | ||
removeItem: (name) => localStorage.removeItem(name), | ||
} | ||
``` | ||
|
||
### How can I rehydrate on storage event | ||
|
||
You can use the Persist API to create your own implementation, | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of an ellipsis, use some example names, like "bears", "fish", "time", "query", or something like that.