Whymess
Whymess

Reputation: 717

When to use dispatch

I want to use dispatch when a form is submitted, but it gives me an error saying it's undefined. I'm not sure what I am doing wrong. I was wondering if someone could spot the error?

Also, I was looking at other peoples code and sometimes they use dispatch and sometimes they just use this.props, which is a better and what is the difference?

  submitRenter(e){
    e.preventDefault()
      dispatch(addUser());
  }



  render() {



  return (
    <form>
      <label>
      <input type="text"/>
      </label>

      <button onClick={this.submitRenter} type="submit">Sumbit</button>

    </form>


      )
  }
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({
      addUser
    }, dispatch)
  };
}


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

Upvotes: 0

Views: 387

Answers (1)

markerikson
markerikson

Reputation: 67459

If you do not supply a mapDispatchToProps function, then connect will use its default behavior and give the component this.props.dispatch. If you do supply a mapDispatch function, then it's up to you what it returns, and you would need to manually include dispatch in that return value.

The point of "binding" action creators is so that you can use them without having to explicitly use the dispatch() function. This is especially useful if you are passing the action creators as props to children that are not connected to Redux.

I personally recommend always binding action creators, and even more than that, using the object shorthand syntax that connect supports for mapDispatch. As an example:

import {addUser} from "./userActions";

const actions = {
    addUser
};

class RegisterRenter {
    submitRenter(e) {
        e.preventDefault();
        this.props.addUser();
    }

    // rendering, etc
}

export default connect(mapState, actions)(RegisterRenter);

For more info, see the Redux FAQ entry on "why don't I have props.dispatch?", and my blog post Idiomatic Redux: Why use action creators?.

Upvotes: 3

Related Questions