You may be thinking, "This looks extremely convoluted, why can't I just pass the dispatch as the props and call this.props.dispatch() in my event handlers? Similar to what we did before?” Like so:
function mapDispatchToProps (dispatch) {
return { dispatch };
};
Whilst that is certainly possible, it couples our component to Redux. Outside Redux, the concept of a dispatch method does not exist. Therefore, using dispatch within our component’s methods effectively ties the component to the Redux environment.
By using the mapDispatchToProps function, we are decoupling the component from Redux. Now, this.props.handleInputChange is just a function we’ve passed down to the component. If we later decide not to use Redux, or we want to re-use the component in a non-Redux environment, we can simply pass down a different function, without changing the component code.
Similarly, we can pull the dispatch call from the handleLogin event handler into mapDispatchToProps:
function mapDispatchToProps (dispatch) {
return {
handleInputChange: (name, event) => { ... },
handleSuccess: token => {
const action = {
type: 'LoginForm:success',
token
}
dispatch(action);
}
};
};
To connect the dots, pass mapStateToProps and mapDispatchToProps into connect. This returns with a function that you can use to wrap the LoginForm component:
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginForm);
Note that the original component (LoginForm) is not mutated. Instead, a newly-wrapped component is created and exported.
Then use handleSuccess in the handleLogin event handler:
class LoginForm extends React.Component {
handleLogin = (event) => {
...
fetch(request)
.then( ... )
.then(this.props.handleSuccess)
.catch(console.error)
}
}
Repeat the same steps for RegistrationForm. As always, run the tests to ensure there are no typos or mistakes.