@@ -6,37 +6,10 @@ nav: 12
6
6
The following pattern can be used to reset the state to its initial value.
7
7
8
8
``` ts
9
- import { create } from ' zustand'
10
-
11
- // define types for state values and actions separately
12
- type State = {
13
- salmon: number
14
- tuna: number
15
- }
16
-
17
- type Actions = {
18
- addSalmon: (qty : number ) => void
19
- addTuna: (qty : number ) => void
20
- reset: () => void
21
- }
22
-
23
- // define the initial state
24
- const initialState: State = {
25
- salmon: 0 ,
26
- tuna: 0 ,
27
- }
28
-
29
- // create store
30
- const useSlice = create <State & Actions >()((set , get ) => ({
31
- ... initialState ,
32
- addSalmon : (qty : number ) => {
33
- set ({ salmon: get ().salmon + qty })
34
- },
35
- addTuna : (qty : number ) => {
36
- set ({ tuna: get ().tuna + qty })
37
- },
9
+ const useSomeStore = create <State & Actions >()((set , get , store ) => ({
10
+ // your code here
38
11
reset : () => {
39
- set (initialState )
12
+ set (store . getInitialState () )
40
13
},
41
14
}))
42
15
```
@@ -58,9 +31,8 @@ const resetAllStores = () => {
58
31
export const create = (<T >() => {
59
32
return (stateCreator : StateCreator <T >) => {
60
33
const store = actualCreate (stateCreator )
61
- const initialState = store .getInitialState ()
62
34
storeResetFns .add (() => {
63
- store .setState (initialState , true )
35
+ store .setState (store . getInitialState () , true )
64
36
})
65
37
return store
66
38
}
@@ -69,6 +41,5 @@ export const create = (<T>() => {
69
41
70
42
## CodeSandbox Demo
71
43
72
- - Basic: https://codesandbox.io/s/zustand-how-to-reset-state-basic-demo-rrqyon
73
- - Advanced: https://codesandbox.io/s/zustand-how-to-reset-state-advanced-demo-gtu0qe
74
- - Immer: https://codesandbox.io/s/how-to-reset-state-advance-immer-demo-nyet3f
44
+ - Basic: https://stackblitz.com/edit/zustand-how-to-reset-state-basic
45
+ - Advanced: https://stackblitz.com/edit/zustand-how-to-reset-state-advanced
0 commit comments