Yu Chen
Yu Chen

Reputation: 7460

Working with component state or props inside Redux mapDispatchToProps

I'm a Redux/React beginner still trying to wrap my held around the component of dispatch within the Redux ecosystem. So far, the way I've issued Redux actions within my components is by directly calling the dispatch() function of my component props:

const mapStateToProps = (state) => {
  return {searchType: state.searchType}
}

export default connect(mapStateToProps)(SearchForm);

And then, I have a handler function tied to an onClick event:

  handleOptionChange(changeEvent) {

    this.setState({selectedOption: changeEvent.target.value});
    this.props.dispatch(setSearchType(this.state.selectedOption));
  }

However, I've been trying to implement mapDispatchToProps instead. This SO post describes some of the benefits to using mapDispatchToProps instead of simply this.props.dispatch. However, I've struggling to find a way to integrate my component props or state into mapDispatchToProps. I want to write something like this:

const mapDispatchToProps = (dispatch) => {
  return {
    setSearchType : dispatch(setSearchType(this.props.option))
  }
}

this.props.option is a prop passed down to identify the configuration being selected for a particular button (in this a Radio Button). And then simply call:

  handleOptionChange(changeEvent) {

    this.setState({selectedOption: changeEvent.target.value});
    this.props.setSearchType(); // <--- this line is new
  }

However, clearly, this in mapDispatchToProps is undefined, since the function is defined outside the scope of my component. In the SO post I referenced, and in the tutorial materials and documentation, mapDispatchToProps is always sending an action that does not rely on a component state/props. What's the best practice for introducing a component's state/props into mapDispatchToProps?

Upvotes: 0

Views: 499

Answers (1)

miles_christian
miles_christian

Reputation: 111

Simply define your dispatcher as a function that accepts the props as parameter:

const mapDispatchToProps = (dispatch) => {
  return {
    setSearchType : option => dispatch(setSearchType(option))
  }
}

Then pass the parameter when calling it:

this.props.setSearchType(this.props.option)

Mind performance issues though when binding onClick to a function on every render. See this article for more info.

Upvotes: 1

Related Questions