MapDispatchToProps with typescript is difficult

Trying to create a simple react crud app with typescript and redux and did the following issue. I have a function that has a signature specified that a human object will be considered as an argument.

export default function savePerson(person: Person) {
    return async (dispatch: any) => {
        let newPerson = await axios.post('/api/people/addPeron', person);
        dispatch(addPersonSuccess(person));
    }
}

      

Now when I try to wire my component to a cut I am having problems with mapDispatchToProps

. Here is my code.

function mapDispatchToProps(dispatch: any) {
  const actions = {
    savePerson: () => dispatch(savePerson())
  }
  return actions;
}

      

The problem is that the savePerson function requires the person to be passed to it, however I have no access to my state in mapDispatchToProps

, and since there are no arguments in the function, my code will not compile. Any ideas?

EDIT SOLUTION:

Here is the code with one change required for this code to work.

function mapDispatchToProps(dispatch: any) {
  const actions = {
    savePerson: (person: Person) => dispatch(savePerson(person))
  }
  return actions;
}

      

I just had to pass the person object to my anonymous function calling dispatch

.

+3


source to share


1 answer


import {IStoreState} from "myGlobalTypes"
import {Dispatch} from "redux";

interface IMyComponentProps {
    savePerson: (person: Person) => Promise<void>;
}
class MyComponent extends React.Component<IMyComponentProps, void>{
    someMethod(person: Person) {
        this.actions.savePerson(person);
    }
}

const WrappedComponent = connect(
   (state: IStoreState, ownProps: {}) => ({
       // here you can map state
   }),
   (dispatch: Dispatch<IStoreState>) => ({
      // savePerson: (person: Person) => dispatch(savePerson(person))
      actions: {
         savePerson: (person: Person) => dispatch(savePerson(person))
      }
   }

      



);

0


source







All Articles