Redux Tutorial on mapDispatchToProps
In the last tutorial, we see that the ToDo component is calling the addToDo action creator to create an action that is dispatch by the store’s dispatch method …
This is a bit verbose. We want the ToDo component to have its own prop called “addItem”. This is going to be a function (yes, props can be functions) that will call the action creator addToDo and dispatch the action that it returns.
We use a function which is typically called “mapDispatchToProps”. This is a function that we write ourselves and pass to the second param of connect() like so…
The function returns an object with property key as the prop you want the component to have. And property value is the function body.
Now our ToDo component has a prop called “addItem” which we can use like this …
There is a shorthand alternative. In the above, the mapDispatchToProps is a function. But it can also be an object with properties whose key is the prop and the value is the action creator that it maps to like this…
This assumes that both addItem and addToDo have the same parameter signatures. And if we happen to call the prop the same name as the action creator, we can shorten the syntax even further. So instead of calling “addItem”, we change its name to “addToDo” …
With ES6, if the key and value of an object be the same, then we can write this as equivalent…
Check that everything works as before …
You can get the source files here.
In the next tutorial, we will use redux-thunk to retrieve ToDos from an API.