Skip to content

Commit

Permalink
Update slices-pattern.md (#2046)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
dbritto-dev and sewera authored Sep 12, 2023
1 parent db76eba commit f3a0fd8
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
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

1 comment on commit f3a0fd8

@vercel
Copy link

@vercel vercel bot commented on f3a0fd8 Sep 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.