While reading through a React/Redux boilerplate, I came across the following code snippet
import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions'
class Signout extends Component {
componentWillMount() {
this.props.signoutUser()
}
render() {
return <div>Bye Bye</div>
}
}
export default connect(null, actions)(Signout)
import axios from 'axios'
import { UNAUTH_USER, AUTH_USER, AUTH_ERROR, FETCH_MESSAGE } from './types'
const ROOT_URL = 'http://localhost:3090'
export function signoutUser() {
localStorage.removeItem('token')
return {
type: UNAUTH_USER
}
}
Question: Can someone explain why the action creator signoutUser()
simply have to return the action object with type: UNAUTH_USER
when called by componentWillMount()
and that action will magically be dispatched?
In other words, I am confused why there is no dispatch
call, such as
dispatch(this.props.signoutUser())
or
dispatch({ type: UNAUTH_USER })
as shown in the redux docs.
This is what mapDispatchToProps is doing under the hood. When you return a value from signOutUser, which is mapped to your component using mapDispatchToProps, the following happens
There are a lot of shorthands we use actually without knowing what is happening under the hood. For example, take the following
is same as
As suggested in comments I think you take a look at mapDispatchToProps, bindActionCreators implementation which can be found in following links
https://github.com/reduxjs/react-redux/blob/3e53ff96ed10f71c21346f08823e503df724db35/src/connect/mapDispatchToProps.js
https://github.com/reduxjs/redux/blob/master/src/bindActionCreators.js