gags
gags

Reputation: 355

dispatch action using bindactioncreator in react-redux

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(Object.assign({},LoginActions), dispatch)
    };
}

In the component, I have this function:

  constructor(props) {
        super(props);
        this.onLogin = this.onLogin.bind(this);
    }

onLogin(loginType){
    LoginActions.loginAction(this.state.user.username, this.state.user.password, loginType, [] , "")
  }

I believed LoginActions.loginAction should be able to dispatch the action but looks like no. It never returns calls the function to be returned from action creator using redux thunk>

For ex.:

export function loginAction(email, password, loginType, products, productIds){    //thunk always returns a function that accepts a dispatch
  console.log("IN LOGIN ACTION")
  console.log("email", email);
  console.log("password", password);
  console.log("login type", loginType)
  console.log("products", products)
  console.log("productids", productIds) //comma separated list of product Id's
  return function (dispatch) {
    console.log("dispatch)
    return LoginAPI.directLogin(cookie.load('sessionID'), email, password, loginType, products, '')
         .then(userinfo => {
            dispatch(login(userinfo))
          }).catch(err=> {
          console.log("error occured", err)
          throw(err);
        });

IN above function, all of the console statements are printed but it never prints "dispatch". I guess I am not calling it the right-way. COuld I get help on this please

Upvotes: 1

Views: 182

Answers (2)

dting
dting

Reputation: 39307

If you are using mapDispatchToProps for connect, you will dispatch the action using:

this.props.actions.loginAction(this.state.user.username, this.state.user.password, loginType, [] , "");

Upvotes: 1

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31203

When you bind your actions it returns an object that you are mapping to actions. This means you can call this.props.actions.loginAction(...) and it will be dispatched.

It will not change the function itself in any way so if you call the function it will just do whatever the function does but not dispatch it anywhere.

Upvotes: 1

Related Questions