Hi recently I encountered the useDispatch hook that supposed to give me an alternative to mapDispatchToProps, and I found very repetitive to do () => dispatch(action(args))
in each onPress so I started to think about something generic. My goal was to make a hook that uses useDispatch()
and wraps the functions that it gets and retuens () => dispatch(theWrappedAction(theActionArgs))
for example if I have an action upCounterActionCreator
that is as following:
export const upCounterActionCreator = (count: number = 1): AppActions => {const action: UpCounterAction = { type: 'UP_COUNTER', count};return action;};
My goal is to do something like this:const [upAfterDispatch] = useActions(upCounterActionCreator);
and then I can do:
<Button onPress={upAfterDispatch(1)} title='+' />
What I tried to do is as following:
export const useActions = (...actions: ((...args: any) => AppActions)[]) => {const dispatch = useDispatch<Dispatch<AppActions>>();const actionsWithDispach: ((...args: any) => () => (...args: any) => AppActions)[] = [];actions.forEach(action => { actionsWithDispach.push((...args: any) => () => (...args: any) => dispatch(action(...args)));});return actionsWithDispach;
};
to put that wrapped function on onPress I need to do
<Button onPress={upAfterDispatch(1)()} title='+' />
- to invoke it, it is not so good option. Then when I do call it the action indeed is being dispatched however when I debug on my payload I have an object insted of count that is as following:it is a class-
What am I doing wrong? What do I need to to in order to:
get the number 1(the count parameter sent in the action payload) instead of the class
invoke the returned functions from useActions and not call it like this
onPress={upAfterDispatch(1)()
** I think that the object received in the args is the react native onPress event, how to avoid it overriding my count argument?Thanks ahead!