-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
66 lines (59 loc) · 1.51 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { create, StateCreator } from 'zustand'
import { immer } from 'zustand/middleware/immer'
interface BearSlice {
bears: number
addBear: () => void
eatFish: () => void
}
interface FishSlice {
fishes: number
addFish: () => void
}
interface SharedSlice {
addBoth: () => void
getBoth: () => void
}
const createBearSlice: StateCreator<
BearSlice & FishSlice,
[],
[],
BearSlice
> = (set) => ({
bears: 0,
// BADKEY is accepted
addBear: () => set((state) => ({ bears: state.bears + 1, BADKEY: 42 })),
eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),
})
const createFishSlice: StateCreator<
BearSlice & FishSlice,
[['zustand/immer', never]],
[],
FishSlice
> = (set) => ({
fishes: 0,
// Because of the immer declaration, "state" is interpreted as Draft<T>, rather
// than Draft<BearSlice & FishSlice>, so "state.bears" is inferred as "any".
addFish: () => set((state) => { state.fishes = 'NOW I AM A STRING' }),
})
const createSharedSlice: StateCreator<
BearSlice & FishSlice,
[],
[],
SharedSlice
> = (set, get) => ({
addBoth: () => {
// you can reuse previous methods
get().addBear()
get().addFish()
// or do them from scratch
// set((state) => ({ bears: state.bears + 1, fishes: state.fishes + 1 })
},
getBoth: () => get().bears + get().fishes,
})
export const useBoundStore = create<BearSlice & FishSlice & SharedSlice>()(
immer((...a) => ({
...createBearSlice(...a),
...createFishSlice(...a),
...createSharedSlice(...a),
}))
)