Skip to content

Commit

Permalink
feat: allow using getters in other getters
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Jan 20, 2020
1 parent a1d2790 commit 859eeb3
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 9 deletions.
7 changes: 7 additions & 0 deletions __tests__/getters.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ describe('Store', () => {
}),
getters: {
upperCaseName: ({ name }) => name.toUpperCase(),
composed: (state, { upperCaseName }) =>
(upperCaseName.value as string) + ': ok',
},
})()
}
Expand Down Expand Up @@ -58,4 +60,9 @@ describe('Store', () => {
aStore.state.a = 'b'
expect(aStore.fromB.value).toBe('b b')
})

it('can use other getters', () => {
const store = useStore()
expect(store.composed.value).toBe('EDUARDO: ok')
})
})
2 changes: 1 addition & 1 deletion src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ export function buildStore<
computedGetters[getterName] = computed(() => {
setActiveReq(_r)
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return getters[getterName](state.value)
return getters[getterName](state.value, computedGetters)
}) as StoreWithGetters<S, G>[typeof getterName]
}

Expand Down
10 changes: 2 additions & 8 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ export function isPlainObject(
export type NonNullObject = Record<any, any>

export interface StoreGetter<S extends StateTree, T = any> {
(state: S): T
// TODO: would be nice to be able to define the getters here
(state: S, getters: Record<string, Ref<any>>): T
}

type TODO = any
Expand All @@ -30,13 +31,6 @@ export type SubscriptionCallback<S> = (
state: S
) => void

export type StoreReactiveGetters<
S extends StateTree,
G extends Record<string, (state: S, getters: any) => any>
> = {
[k in keyof G]: G[k] extends (state: S, getters: any) => infer V ? V : never
}

export type StoreWithGetters<
S extends StateTree,
G extends Record<string, StoreGetter<S>>
Expand Down

0 comments on commit 859eeb3

Please sign in to comment.