trebek1
trebek1

Reputation: 775

Spreading Redux Actions does not work in mapDispatchToProps

My mapDispatchToProps works like this:

const mapDispatchToProps = dispatch => ({
  getCourts: () => dispatch(courtActions.getCourts()),
  selectStyle: style => dispatch(courtActions.selectStyle(style)),
  selectPoint: index => dispatch(courtActions.selectPoint(index)),
  sortPoints: sort => dispatch(courtActions.sortPoints(sort))
});

I want to write it like:

const mapDispatchToProps = dispatch => ({
      ...courtActions,
});

but when I do that none of my actions work (they dont get dispatched). I'm sure this is something obvious. But what is going on here?

Here is the actions file:

export const getCourts = () => dispatch =>
  axios
    .get("/courts")
    .then(response => dispatch({ type: GET_COURTS, payload: response.data }));

export const selectStyle = style => ({ type: SELECT_STYLE, payload: style });

export const sortPoints = type => ({ type: SORT_POINTS, payload: type });

export const selectPoint = index => ({ type: SELECT_POINT, payload: index });

export default {
  getCourts,
  selectStyle,
  sortPoints,
  selectPoint
};

Upvotes: 2

Views: 106

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281874

mapDispatchToProps takes an object too, which you can use instead of defining a function as mapDispatchToProps which would need to return functions that use dispatch.

According to the docs:

If an object is passed, each function inside it is assumed to be a Redux action creator. An object with the same function names, but with every action creator wrapped into a dispatch call so they may be invoked directly, will be merged into the component’s props.

Example

const mapDispatchToProps = courtActions;

Or you can simply pass courtActions as the second parameter to connect like

connect(mapStateToProps, courtActions)(MyComponent);

Upvotes: 4

Deepak Singh
Deepak Singh

Reputation: 136

as per my understanding mapDispatchToProps is function which takes dispatch as parameter and thats a dispatcher which dispatch massages to reducers. you cannot use like you want to use.

Upvotes: 0

Related Questions