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

fix(docs): Add how to reset state to docs/guides section #1236

Merged
merged 6 commits into from
Aug 29, 2022
Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions docs/guides/how-to-reset-state.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
title: How to reset state
nav: 18
---

The following pattern can be used to reset the state to its initial value.

```ts
import create from 'zustand'

// define types for state values and actions separately
type State = {
salmon: number
tuna: number
}

type Actions = {
addSalmon: (qty: number) => void
addTuna: (qty: number) => void
reset: () => void
}

// define the initial state
const initialState: State = {
salmon: 0,
tuna: 0,
}

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

addSalmon: (qty: number) => {
set({ salmon: get().salmon + qty })
},

addTuna: (qty: number) => {
set({ tuna: get().tuna + qty })
},

reset: () => {
set(initialState)
},
}))
```

Resetting multiple stores at once instead of individual stores

```ts
import _create, { StateCreator, StoreApi, UseBoundStore } 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()

resetters.push(() => {
slice.setState(initialState, true)
})

return slice
}

export const resetAllSlices = () => {
for (const resetter of resetters) {
resetter()
}
}
```

## CodeSandbox Demo

https://codesandbox.io/s/zustand-how-to-reset-state-demo-gtu0qe