Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6212

Trying to wrap dispatch function in react redux

$
0
0

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-

enter image description here

What am I doing wrong? What do I need to to in order to:

  1. get the number 1(the count parameter sent in the action payload) instead of the class

  2. 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!


Viewing all articles
Browse latest Browse all 6212

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>