reactjsreact-reduxredux-middleware

TypeError: this.props.loginActionCreater is not a function in react-redux


I am new for react redux here I am trying to call two actions in component. There is login page after click on button I am calling one action that will fetch auth_token then that token I am using in componentWillReceiveProps() for calling another action.below is my code

Issue: While I am click on button its showing an error which I have mentioned in questions title.

UI:

<Button
        block
        bsSize="large"
        disabled={!this.validateForm()}
        onClick={this.handleSubmit.bind(this)}
      >
        Login
      </Button>

functionality:

import React, { Component } from 'react'
import { Button, FormGroup, FormControl, ControlLabel } from 'react- 
 bootstrap';
import { loginActionCreater } from '../../actions/index';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchListOfCandidate } from 
'../../actions/FetchCandidateAction/FetchCandidateAction';

handleSubmit() {
this.props.loginActionCreater(this.state.email, this.state.password);
}

componentWillReceiveProps(nextProps) {
if (nextProps.token) {
  this.props.fetchListOfCandidate(nextProps.token);
  history.push('/HeaderComponents');
}
}


function mapStateToProps(state) {
 return {
error: state.login.error,
token: state.login.token
}
}

function mapDispatchToProps(dispatch) {
 return {
  actions: {
          loginActionCreater: bindActionCreators(loginActionCreater, dispatch),
          fetchListOfCandidate: bindActionCreators(fetchListOfCandidate, dispatch)
         }
 }
 }

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

If I just dispatch single action its working fine but while dispatching two actions its showing error which mentioned in title.

here is how I am dispatching single action which working fine:

function mapDispatchToProps(dispatch) {
 return bindActionCreators({ loginActionCreater }, dispatch);
 }

what I am doing wrong please correct me if someone knows.Thanks for any help!


Solution

  • The problem is in your mapDispatchToProps method when you have two actions. Look here:

    function mapDispatchToProps(dispatch) {
      return {
        actions: {
          loginActionCreater: bindActionCreators(loginActionCreater, dispatch),
          fetchListOfCandidate: bindActionCreators(fetchListOfCandidate, dispatch)
        }
      }
    }
    

    You are returning an object, with the key action. When you have a single action, your mapDispatchToProps looks like this:

    function mapDispatchToProps(dispatch) {
      return bindActionCreators({ loginActionCreater }, dispatch);
    }
    

    Its not returning an object with the key action.

    If you'd like to keep your implementation of mapDispatchToProps with two action. Please try invoking your action like this:

    this.props.actions.loginActionCreater()