prajeesh
prajeesh

Reputation: 2382

Action invoked without dispatching it - Redux

I am trying to understand redux and is having some doubts regarding mapDispatchToProps.

The code is as follows.

import * as actions  from '../../redux/actions';
import './style.scss'

class Center extends Component {
  componentDidMount() {
    this.props.getCenters();
  }

  ...
}
export default connect(state => ({
  ...state.center,
}),{
  ...actions,
})(Center);

Actions file is defined as follows.

export const getCenters = () => ({
  type: types.CENTERS_REQUEST,
});

When the component is mounted, this.props.getCenters() is called and the action is dispatched and everything works as expected.

The question is,

There is no dispatch mentioned in the definition of getCenters. So, how is this action invoked without dispatching it?

Upvotes: 0

Views: 69

Answers (1)

Tomer
Tomer

Reputation: 1568

Redux injects dispatch (Implicitly) to your actions in connect:

export default connect(state => ({
  ...state.center,
}),{
  ...actions,
})(Center);

If we abstract this a bit, we can watch how it happens (Explicitly):

function mapDispatchToProps(dispatch) {
    return {
        getCenters: () => dispatch(getCenters())
    }
}

export default connect(state => ({
  ...state.center,
}), mapDispatchToProps)(Center);

As a result, getCenters gets equipped with dispatch.

Upvotes: 2

Related Questions