mirror of
https://github.com/pmndrs/zustand.git
synced 2025-12-08 19:45:52 +00:00
Update slices-pattern.md (#2046)
* Update slices-pattern.md * Update typescript.md * Fix format * Update typescript.md Co-authored-by: Blazej Sewera <code@sewera.dev> * Update typescript.md Co-authored-by: Blazej Sewera <code@sewera.dev> --------- Co-authored-by: Blazej Sewera <code@sewera.dev>
This commit is contained in:
parent
db76eba813
commit
f3a0fd802b
@ -67,13 +67,10 @@ export default App
|
||||
You can update multiple stores, at the same time, in a single function.
|
||||
|
||||
```js
|
||||
import { createBearSlice } from './bearSlice'
|
||||
import { createFishSlice } from './fishSlice'
|
||||
|
||||
export const createBearFishSlice = (set) => ({
|
||||
export const createBearFishSlice = (set, get) => ({
|
||||
addBearAndFish: () => {
|
||||
createBearSlice(set).addBear()
|
||||
createFishSlice(set).addFish()
|
||||
get().addBear()
|
||||
get().addFish()
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
@ -367,6 +367,17 @@ interface BearSlice {
|
||||
addBear: () => void
|
||||
eatFish: () => void
|
||||
}
|
||||
|
||||
interface FishSlice {
|
||||
fishes: number
|
||||
addFish: () => void
|
||||
}
|
||||
|
||||
interface SharedSlice {
|
||||
addBoth: () => void
|
||||
getBoth: () => void
|
||||
}
|
||||
|
||||
const createBearSlice: StateCreator<
|
||||
BearSlice & FishSlice,
|
||||
[],
|
||||
@ -378,10 +389,6 @@ const createBearSlice: StateCreator<
|
||||
eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),
|
||||
})
|
||||
|
||||
interface FishSlice {
|
||||
fishes: number
|
||||
addFish: () => void
|
||||
}
|
||||
const createFishSlice: StateCreator<
|
||||
BearSlice & FishSlice,
|
||||
[],
|
||||
@ -392,9 +399,26 @@ const createFishSlice: StateCreator<
|
||||
addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
|
||||
})
|
||||
|
||||
const useBoundStore = create<BearSlice & FishSlice>()((...a) => ({
|
||||
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,
|
||||
})
|
||||
|
||||
const useBoundStore = create<BearSlice & FishSlice & SharedSlice>()((...a) => ({
|
||||
...createBearSlice(...a),
|
||||
...createFishSlice(...a),
|
||||
...createSharedSlice(...a),
|
||||
}))
|
||||
```
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user