Skip to content

Commit

Permalink
Fix nested actions not bound (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
albertogasparin authored Jul 9, 2019
1 parent 1d23b39 commit f1539fa
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 7 deletions.
13 changes: 10 additions & 3 deletions examples/advanced-flow/components/user/actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,19 @@ const USERS: UserModel[] = [
{ id: '2', name: 'Paul' },
];

export const load = (): Action<State> => async ({ setState, getState }) => {
if (getState().loading) return;

export const setLoading = (): Action<State> => ({ setState }) => {
setState({
loading: true,
});
};

export const load = (): Action<State> => async ({
setState,
getState,
actions,
}) => {
if (getState().loading) return;
actions.setLoading();
// simulate async call
await new Promise(r => setTimeout(r, 1000));
setState({
Expand Down
16 changes: 15 additions & 1 deletion src/store/__tests__/bind-actions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ describe('bindAction', () => {
{
setState: expect.any(Function),
getState: storeStateMock.getState,
actions: actionsMock,
actions: expect.objectContaining({
increase: expect.any(Function),
decrease: expect.any(Function),
}),
dispatch: expect.any(Function),
},
containerProps
Expand Down Expand Up @@ -61,4 +64,15 @@ describe('bindActions', () => {
decrease: expect.any(Function),
});
});

it('should return actions object with actions bound', () => {
const state = { data: null };
storeStateMock.getState.mockReturnValue(state);
actionsMock.increase.mockReturnValue(({ actions }) => actions.decrease());
actionsMock.decrease.mockReturnValue(({ getState }) => getState());
const result = bindActions(actionsMock, storeStateMock);
const output = result.increase();

expect(output).toEqual(state);
});
});
6 changes: 3 additions & 3 deletions src/store/bind-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const bindAction = (
actionFn,
actionKey,
getContainerProps = () => {},
otherActions = {}
boundActions = {}
) => {
// Setting mutator name so we can log action name for better debuggability
const dispatch = (thunkFn, actionName = `${actionKey}.dispatch`) =>
Expand All @@ -20,7 +20,7 @@ export const bindAction = (
? namedMutator(storeState, actionName)
: storeState.mutator,
getState: storeState.getState,
actions: otherActions,
actions: boundActions,
dispatch,
},
getContainerProps()
Expand All @@ -34,6 +34,6 @@ export const bindActions = (
getContainerProps = () => ({})
) =>
Object.keys(actions).reduce((acc, k) => {
acc[k] = bindAction(storeState, actions[k], k, getContainerProps, actions);
acc[k] = bindAction(storeState, actions[k], k, getContainerProps, acc);
return acc;
}, {});

0 comments on commit f1539fa

Please sign in to comment.