Skip to content

Commit

Permalink
docs: example and readme
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisvander committed Mar 3, 2024
1 parent 04089ff commit 977ab58
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,13 @@ const computeState = (state) => ({

const useStore = create(
computed(
(set) => ({
(set, get) => ({
count: 1,
inc: () => set((state) => ({ count: state.count + 1 })),
dec: () => set((state) => ({ count: state.count - 1 })),
// get() function has access to ComputedStore
square: () => set(() => ({ count: get().countSq })),
root: () => set((state) => ({ count: Math.floor(Math.sqrt(state.count)) })),
}),
computeState
)
Expand Down Expand Up @@ -62,6 +65,9 @@ const useStore = create<Store>()(
count: 1,
inc: () => set((state) => ({ count: state.count + 1 })),
dec: () => set((state) => ({ count: state.count - 1 })),
// get() function has access to ComputedStore
square: () => set(() => ({ count: get().countSq })),
root: () => set((state) => ({ count: Math.floor(Math.sqrt(state.count)) })),
}),
computeState
)
Expand Down Expand Up @@ -90,7 +96,7 @@ A fully-featured example can be found under the "example" directory.

## With Middleware

Here's an example with middleware. Works as expected.
Here's an example with the Immer middleware. Note that types may not be as you expect when using Immer, as it derives the SetState type from the output of GetState, where `zustand-computed` makes SetState only allow the regular Store and the GetState return both the store and the computed store.

```ts
const useStore = create<Store>()(
Expand Down
25 changes: 12 additions & 13 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,19 @@ function computeState(state: Store): ComputedStore {
const useStore = create<Store>()(
devtools(
computed(
(set, get) => ({
count: 1,
inc: () =>
set((state) => {
// return { countSq: 1 } would error here; SetState does not include ComputedStore
return { count: state.count + 1 }
}),
dec: () => set((state) => ({ count: state.count - 1 })),
// the get() function has access to the computed store
square: () => set({ count: get().countSq }),
root: () => set({ count: Math.floor(Math.sqrt(get().count)) }),
}),
computeState,
(set, get) =>
({
count: 1,
inc: () =>
set((state) => {
// return { countSq: 1 } would error here; SetState does not include ComputedStore
return { count: state.count + 1 }
}),
dec: () => set((state) => ({ count: state.count - 1 })),
// the get() function has access to the computed store
square: () => set({ count: get().countSq }),
root: () => set({ count: Math.floor(Math.sqrt(get().count)) }),
}) satisfies Store,
),
),
)
Expand Down

0 comments on commit 977ab58

Please sign in to comment.