Naveed Aheer
Naveed Aheer

Reputation: 1825

How to dispatch more than one action in mapDispatchToProps in react-redux

There are three functions in mapDispatchToProps. I want to use any function from them in constructor of React Component but when I use console.log(this.props)it gives undefined how Can I use these functions in constructor to load data from firebase database?

mapDispatchToProps

const mapDispatchToProps = (dispatch) => {
    return {
        addProductRequest: (data) => {
            console.log(data)
            dispatch(AddNewProduct(data))
        },
        loadProducts: () => {
            dispatch(ViewProducts())
        },
        loadStores: () => {
            dispatch(ViewStores())
        },
    }
}

Constructor

constructor() {
    super();
    this.state = {
        products: [],
        stores: [],
        currentProduct: [],
        stockAvailable: [],
        productName: '',
        description: '',
        qty: 0,
        unitPrice: 0,
        storeName: '',
        selectedProduct: '',
        productNameInStock: '',
        productQtyInStock:0
    }
    console.log(this.props)

    this.props.loadProducts();
    this.props.loadStores();

    this.submit = this.submit.bind(this);
    this.inputHandler = this.inputHandler.bind(this);
}

it gives an error

Uncaught TypeError: Cannot read property 'loadProducts' of undefined

Upvotes: 3

Views: 5885

Answers (2)

Naveed Aheer
Naveed Aheer

Reputation: 1825

Now its Working , I forgot to pass props in constructor

constructor(props) {
    super();
    this.state = {
        products: [],
        stores: [],
        currentProduct: [],
        stockAvailable: [],
        productName: '',
        description: '',
        qty: 0,
        unitPrice: 0,
        storeName: '',
        selectedProduct: '',
        productNameInStock: '',
        productQtyInStock:0
    }
    console.log(props)

    props.loadProducts();
    props.loadStores();

    this.submit = this.submit.bind(this);
    this.inputHandler = this.inputHandler.bind(this);
}

Upvotes: 0

Vlad Dekhanov
Vlad Dekhanov

Reputation: 1084

You would use bindActionCreators from redux, f.e.:

const mapDispatchToProps = (dispatch) => {
    return {
        ...bindActionCreators({ loadProducts, loadStores }, dispatch)
    }
}

In that case you will be able to create action through this.props.loadProducts() in component.

Upvotes: 7

Related Questions