Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

mapDispatchToProps and connect

During the previous lesson, we managed to connect a component's props, with corresponding variables in global state under a new component, by using the connect function to return this new component, which used an existing component as template and makes the connection with the redux store at the same time.

The second step, is to actually connect component's functions, to change the variables in the global state. The logic is very similar. We will attempt to do it with a new DepositButton component, that renders a single button component, which when clicked, executes a function. This function is connected with redux state, and actually triggers a dispatch of the depositAction function (which actually is taken by the reducer and adds 50 dollars) to the account. 

How? Simply by using another function, which again you can name as you like but as a convention usually is named something like mapDispatchToProps. This function accepts an argument, which is the dispatch function, and returns an object that holds local component's function props, and arrow functions that dispatch corresponding actions as values. Exactly as shown above.

Thus anytime, the button is clicked, the depositAction with argument of 50 (for 50 dollars) is dispatched and the reducer updates the state accordingly. 

Attention: Don't forget to import the action functions to the app.js file in order to place them inside the dispatch!

Then exactly like before we create a new fresh component which is returned from the connect function. This component does NOT have props mapped to state though, so the first argument will be left as null (but MUST be there!!), the second argument will be the function that maps dispatch to props, and as usual inside the second parentheses the component where all these things happen as base.

Attention again! Don't forget to place the new fresh component inside the App component, below the heading now!