Skip to content

Commit

Permalink
feat(hooks): add useGetters hook
Browse files Browse the repository at this point in the history
  • Loading branch information
u3u committed Jul 8, 2019
1 parent 607dfd1 commit 49376cb
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/__tests__/useGetters.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import useGetters from '../useGetters';
import renderHook from '../util/renderHook';

describe('useGetters', () => {
it('should be defined', () => {
expect(useGetters).toBeDefined();
});

it('should update getters', () => {
type Inject = { plusOne: number; minusOne: number };
const { vm } = renderHook<Inject>(() => ({
...useGetters(['plusOne']),
...useGetters('test', ['minusOne']),
}));
expect(vm.plusOne).toBe(1);
expect(vm.minusOne).toBe(-1);

vm.$store.commit('increment');
vm.$store.commit('test/decrement');

expect(vm.plusOne).toBe(2);
expect(vm.minusOne).toBe(-2);
});
});
40 changes: 40 additions & 0 deletions src/ts/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {
Mapper,
MapperWithNamespace,
MapperForState,
MapperForStateWithNamespace,
FunctionMapper,
FunctionMapperWithNamespace,
Computed,
MutationMethod,
Commit,
Dictionary,
ActionMethod,
Dispatch,
} from 'vuex';

interface MapperRestParameters<R> {
(...args: any[]): Dictionary<R>;
}

export type MapperState = Mapper<Computed> &
MapperWithNamespace<Computed> &
MapperForState &
MapperForStateWithNamespace &
MapperRestParameters<Computed>;

export type MapperMutations = Mapper<MutationMethod> &
MapperWithNamespace<MutationMethod> &
FunctionMapper<Commit, MutationMethod> &
FunctionMapperWithNamespace<Commit, MutationMethod> &
MapperRestParameters<ActionMethod>;

export type MapperGetters = Mapper<Computed> &
MapperWithNamespace<Computed> &
MapperRestParameters<Computed>;

export type MapperActions = Mapper<ActionMethod> &
MapperWithNamespace<ActionMethod> &
FunctionMapper<Dispatch, ActionMethod> &
FunctionMapperWithNamespace<Dispatch, ActionMethod> &
MapperRestParameters<ActionMethod>;
19 changes: 19 additions & 0 deletions src/useGetters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { computed } from 'vue-function-api';
import { mapGetters } from 'vuex';
import { MapperGetters } from './ts';
import { getRuntimeVM } from './util/runtime';

const useGetters: MapperGetters = (...args) => {
// @ts-ignore
const getters = mapGetters(...args);
const mapper = {};
Object.keys(getters).forEach((key) => {
// TypeError: Cannot read property '_modulesNamespaceMap' of undefined
// You must get `runtimeVM` in real time in the calculation properties.
mapper[key] = computed(() => getters[key].call(getRuntimeVM()));
});

return mapper;
};

export default useGetters;

0 comments on commit 49376cb

Please sign in to comment.