Skip to content

Commit

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

interface InjectMutations {
increment: Function;
decrement: Function;
}

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

it('should be defined mutations', () => {
const { vm } = renderHook<InjectMutations>(() => ({
...useMutations(['increment']),
...useMutations('test', ['decrement']),
}));

expect(vm.increment).toBeDefined();
expect(vm.decrement).toBeDefined();
});

it('should update count state', () => {
const { vm } = renderHook<InjectMutations>(() => ({
...useMutations(['increment']),
...useMutations('test', ['decrement']),
}));

expect(vm.$store.state.count).toBe(0);
expect(vm.$store.state.test.count).toBe(0);

vm.increment();
vm.decrement();

expect(vm.$store.state.count).toBe(1);
expect(vm.$store.state.test.count).toBe(-1);
});
});
17 changes: 17 additions & 0 deletions src/useMutations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { mapMutations } from 'vuex';
import { MapperMutations } from './ts';
import { getRuntimeVM } from './util/runtime';

const useMutations: MapperMutations = (...args) => {
// @ts-ignore
const mutations = mapMutations(...args);
const vm = getRuntimeVM();
const mapper = {};
Object.keys(mutations).forEach((key) => {
mapper[key] = mutations[key].bind(vm);
});

return mapper;
};

export default useMutations;

0 comments on commit b38358c

Please sign in to comment.