Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapDispatchToProps with typescript is being difficult

Trying to build a simple react crud app with typescript and redux and ran in to the following issue. I have a function that has the specified signature that it will take a person object as an argument as seen here.

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 am trying to connnect my component to redux I am having trouble with the mapDispatchToProps. Here is my code.

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

The issue is that the savePerson function requires a person to be passed to it, however I do not have access to my state in the mapDispatchToProps, and since the function is missing arguments my code wont compile. Any ideas?

EDIT WITH SOLUTION:

Here is the code with the one change needed to make this code 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 that is calling dispatch.

like image 874
Chaim Friedman Avatar asked May 05 '17 16:05

Chaim Friedman


People also ask

Should I use TypeScript with React-Redux?

As of React-Redux v8, React-Redux is fully written in TypeScript, and the types are included in the published package. The types also export some helpers to make it easier to write typesafe interfaces between your Redux store and your React components.

Does Reactjs use TypeScript?

Create React App supports TypeScript out of the box. You can also add it to an existing Create React App project, as documented here.


1 Answers

import { AnyAction } from "redux";
import { ThunkDispatch } from "redux-thunk";
import { savePerson } from "../myActions";

// IExtraDispatchArguments usually is empty
import { IExtraDispatchArguments, IStoreState } from "../myGlobalTypes"

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: ThunkDispatch<IStoreState, IExtraDispatchArguments, AnyAction>)) => ({
      // savePerson: (person: Person) => dispatch(savePerson(person))
      actions: {
         savePerson: (person: Person) => dispatch(savePerson(person))
      }
   }
);
like image 132
Yozi Avatar answered Oct 08 '22 01:10

Yozi