Skip to content

Commit b38358c

Browse files
committed
feat(hooks): add useMutations hook
1 parent 49376cb commit b38358c

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/__tests__/useMutations.test.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import useMutations from '../useMutations';
2+
import renderHook from '../util/renderHook';
3+
4+
interface InjectMutations {
5+
increment: Function;
6+
decrement: Function;
7+
}
8+
9+
describe('useMutations', () => {
10+
it('should be defined', () => {
11+
expect(useMutations).toBeDefined();
12+
});
13+
14+
it('should be defined mutations', () => {
15+
const { vm } = renderHook<InjectMutations>(() => ({
16+
...useMutations(['increment']),
17+
...useMutations('test', ['decrement']),
18+
}));
19+
20+
expect(vm.increment).toBeDefined();
21+
expect(vm.decrement).toBeDefined();
22+
});
23+
24+
it('should update count state', () => {
25+
const { vm } = renderHook<InjectMutations>(() => ({
26+
...useMutations(['increment']),
27+
...useMutations('test', ['decrement']),
28+
}));
29+
30+
expect(vm.$store.state.count).toBe(0);
31+
expect(vm.$store.state.test.count).toBe(0);
32+
33+
vm.increment();
34+
vm.decrement();
35+
36+
expect(vm.$store.state.count).toBe(1);
37+
expect(vm.$store.state.test.count).toBe(-1);
38+
});
39+
});

src/useMutations.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { mapMutations } from 'vuex';
2+
import { MapperMutations } from './ts';
3+
import { getRuntimeVM } from './util/runtime';
4+
5+
const useMutations: MapperMutations = (...args) => {
6+
// @ts-ignore
7+
const mutations = mapMutations(...args);
8+
const vm = getRuntimeVM();
9+
const mapper = {};
10+
Object.keys(mutations).forEach((key) => {
11+
mapper[key] = mutations[key].bind(vm);
12+
});
13+
14+
return mapper;
15+
};
16+
17+
export default useMutations;

0 commit comments

Comments
 (0)