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 slices-pattern.md #2046

Merged
merged 5 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
9 changes: 3 additions & 6 deletions docs/guides/slices-pattern.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
},
})
```
Expand Down
34 changes: 29 additions & 5 deletions docs/guides/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
[],
Expand All @@ -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,
[],
Expand All @@ -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),
}))
```

Expand Down