Skip to content
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

Update how to reset state doc #1495

Merged
merged 6 commits into from Dec 27, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 12 additions & 17 deletions docs/guides/how-to-reset-state.md
Expand Up @@ -27,7 +27,7 @@ const initialState: State = {
}

// create store
const useSlice = create<State & Actions>((set, get) => ({
const useSlice = create<State & Actions>()((set, get) => ({
...initialState,

addSalmon: (qty: number) => {
Expand All @@ -44,30 +44,24 @@ const useSlice = create<State & Actions>((set, get) => ({
}))
```

Resetting multiple stores at once instead of individual stores
Resetting multiple stores at once

```ts
import _create, { StateCreator, StoreApi, UseBoundStore } from 'zustand'
import _create, { StateCreator } from 'zustand'

const resetters: (() => void)[] = []

export const create = <TState extends unknown>(
createState: StateCreator<TState> | StoreApi<TState>
): UseBoundStore<StoreApi<TState>> => {
// We need to use createState as never to support StateCreator<TState> and
// StoreApi<TState> at the same time.
// We also need to re-type slice to UseBoundStore<StoreApi<TState>>
const slice: UseBoundStore<StoreApi<TState>> = _create(createState as never)
const initialState = slice.getState()

export const create = (<T extends unknown>(f: StateCreator<T> | undefined) => {
if (f === undefined) return create
const store = _create(f)
const initialState = store.getState()
resetters.push(() => {
slice.setState(initialState, true)
store.setState(initialState, true)
})
return store
}) as typeof _create

return slice
}

export const resetAllSlices = () => {
export const resetAllStores = () => {
for (const resetter of resetters) {
resetter()
}
Expand All @@ -78,3 +72,4 @@ export const resetAllSlices = () => {

- Basic: https://codesandbox.io/s/zustand-how-to-reset-state-basic-demo-rrqyon
- Advanced: https://codesandbox.io/s/zustand-how-to-reset-state-advanced-demo-gtu0qe
- Immer: https://codesandbox.io/s/how-to-reset-state-advance-immer-demo-nyet3f
dbritto-dev marked this conversation as resolved.
Show resolved Hide resolved