mapDispatchToProps
Learn how to provide the action creators as props to your component which can then be dispatched.
We'll cover the following
Dispatching actions via mapDispatchToProps
Let’s look at the second parameter for the connect()
function, mapDispatchToProps
:
const mapDispatchToProps = (dispatch, ownProps) => {
// ...
};
Or, it can alternatively be written as follows:
const mapDispatchToProps = {
// ...
};
While mapStateToProps
grants us access to the store to read data, mapDispatchToProps
allows us to change the store’s data with write access. The mapDispatchToProps
function’s
signature looks similar to that of mapStateToProps
. However, instead of receiving the whole state as a first parameter, we receive the dispatch
method of the store that we connect to. The second parameter of mapDispatchToProps
form ownProps
-the props of the component
itself - that is passed to the component. It is also possible to pass a mapDispatchToProps
object
instead of a function to the connect()
call. But let’s look at that later. First, let’s investigate how to use mapDispatchToProps
.
Manipulating todos in our to-do app
We want to add the possibility of adding new todos
to our TodoList
, mark them as resolved, and remove them from the list completely. We now want to add the option for a user to dispatch the actions
ADD_TODO
, REMOVE_TODO
, and CHANGE_TODO_STATUS
by interacting with our application:
Get hands-on with 1200+ tech skills courses.