Skip to content

Commit 1106ade

Browse files
committed
feat(hooks): add useActions hook
1 parent b38358c commit 1106ade

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

src/__tests__/useActions.test.ts

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

src/useActions.ts

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

0 commit comments

Comments
 (0)