abu abu
abu abu

Reputation: 7022

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 ?

Upvotes: 2

Views: 406

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281726

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 });

Upvotes: 1

Vu Luu
Vu Luu

Reputation: 790

Your should update mapDispatchToProps method a little bit. In addition, you should export it to writing test.

import { bindActionCreators } from 'redux';

export const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(
    getAddress,
    dispatch,
  ),
})

Upvotes: 0

Harish
Harish

Reputation: 1911

I think, initially in store the address is undefined. correct? and the getAddress action will set the address value.

Here is what you missed, 1) you have dispatch the action. you can use any of following

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

or

import { bindActionCreators } from "redux";

    const mapDispatchToProps = dispatch => bindActionCreators({getAddress}, dispatch)

Upvotes: 1

Related Questions