Search code examples
reduxreact-reduxredux-thunk

How to use mapDispatchToProps


I am learning Redux React. How to use mapDispatchToProps ? My code is like below

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getAddress } from '../store/actions/addressActions';

class Dashboard extends Component {
    componentDidMount = () => {
        this.props.getAddress();
    };

    render() {
        return <div>Hello { console.log(this.props) } </div>;
    }
}

const mapStateToProps = state => ({
    address: state.address
});

const mapDispatchToProps = dispatch => ({
    getAddress
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Dashboard);

I am getting console output like below

enter image description here

Where I am doing mistake ? How to use mapDispatchToProps properly ?


Solution

  • Either you define mapDispatchToProps as an object or you return the dispatched function from mapDispatchToProps instead of an object

    Using first approach your mapStateToProps will look like

    const mapDispatchToProps = {
        getAddress
    };
    

    Using second approach it would look like

    const mapDispatchToProps = dispatch => ({
        getAddress: (...args) => dispatch(getAddress(...args));
    });
    

    Also since you are using combineReducers you need to change how you access the state in mapStateToProps

    const mapStateToProps = state => ({ address: state.addressReducer.address });