faraz
faraz

Reputation: 2733

react mapDispatchToProps bindActionCreator

I am having a difficult time trying to understand mapDispatchToProps

here's a mapDispatchToProps function being used

const mapDispatchToProps = () => {
  return {
    addItem: addItem
  };
};

So, what's exactly happening here is that the addItem function is now available as a prop to the react component, right?

so, then why do we need to use bindActionCreators and do this

const mapDispatchToProps = (dispatch) => {
  /* code change */
  return bindActionCreators({
    addItem: addItem
  }, dispatch);
};

what's exactly happening, especially in these lines

return bindActionCreators({
        addItem: addItem
      }, dispatch);

And why couldnt the previous code without the bindActionCreator work?

Upvotes: 2

Views: 197

Answers (1)

DoXicK
DoXicK

Reputation: 4812

to "send an action" (aka: dispatching) you need to dispatch(actionCreator())

let's assume addItem is function addItem() { return {type: 'addItem', payload: data}; };

addItem is a function that returns an action. It's an actionCreator (hence: bind actionCreator), but does not dispatch it. You still have to dispatch the resulting action.

mapDispatchToProps gives you the dispatch function which you need to then dispatch that action.

Here's a couple of viable examples:

const mapDispatchToProps = (dispatch) => {
    return {
        addItem: () => dispatch( addItem() ),
        addItemInline: () => dispatch( {type: 'addItem', payload: 'data'} )
    }
};

bindActionCreators does, in essence, nothing more than this:

const bindActionCreators = (actionCreators, dispatch) => {
    let boundActionCreators = {};
    return Object.keys(actionCreators).forEach(key => {
        boundActionCreators[key] = () => {
            dispatch( actionCreators[key]() );
        };
    });
    return boundActionCreators;
};

or, more verbose: for every actionCreator in the object you pass it, it returns a new function that dispatches the result of the actionCreator.

Upvotes: 3

Related Questions