fix(docs): Update persisting-store-data.md (#1136)

* Update persisting-store-data.md

Add context for TypeScript users.

* Update persisting-store-data.md

Switch to Q and A section

* run prettier

Co-authored-by: daishi <daishi@axlight.com>
This commit is contained in:
Charles Kornoelje 2022-07-26 06:14:47 -04:00 committed by GitHub
parent cf46b42455
commit 5a49d20a27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -541,3 +541,31 @@ export const withStorageDOMEvents = (store: StoreWithPersist) => {
const useBoundStore = create(persist(...))
withStorageDOMEvents(useBoundStore)
```
### How do I use with TypeScript?
Basic typescript usage doesn't require anything special except for writing `create<State>()(...)` instead of `create(...)`.
```tsx
import create from 'zustand'
import { persist } from 'zustand/middleware'
interface MyState {
fishes: number
addAFish: () => void
}
export const useFishStore = create<MyState>()(
persist(
(set, get) => ({
fishes: 0,
addAFish: () => set({ fishes: get().fishes + 1 }),
}),
{
name: 'food-storage', // name of item in the storage (must be unique)
getStorage: () => sessionStorage, // (optional) by default the 'localStorage' is used
partialize: (state) => ({ fishes: state.fishes }),
}
)
)
```