user10022985
user10022985

Reputation:

Passing multiple functions into mapDispatchToProps in redux connect function

I am trying to understand the connect function in redux.

I have this:

  connect(undefined, (dispatch, { setState }) => ({
    ...
  }))

However, I also want to pass through this:

{ match }: { match: Match }

In a similar fashion, like this:

  connect(undefined, (dispatch, { match }: { match: Match }) => ({
    ...
  }))

How would I combine the two? I am looking for something along the lines of this (obviously this doesn't work)

  connect(undefined, (dispatch, { setState, { match }: { match: Match } }) => ({
    ...
  }))

This connect function, along with other functions, is wrapped in a compose

Upvotes: 3

Views: 3864

Answers (2)

Mark C.
Mark C.

Reputation: 6450

For what it's worth - do not pass around setState - that's an anti-pattern.

This is the common syntax/construction for connect regarding a component :

import { connect } from 'react-redux'

const TodoItem = ({ todo, destroyTodo }) => {
  return (
    <div>
      {todo.text}
      <span onClick={destroyTodo}> x </span>
    </div>
  )
}

const mapStateToProps = state => {
  return {
    todo: state.todos[0]
  }
}

const mapDispatchToProps = dispatch => {
  return {
    destroyTodo: () =>
      dispatch({
        type: 'DESTROY_TODO'
      })
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoItem)

Per your question, let's break the syntax down a little easier without all of the properties and look at it as simply as possible :

(dispatch) => {
    test : (dispatch, setState /* don't do this */) => { 
        dispatch('do a thing')
    } 
}

Upvotes: 2

Roman Mahotskyi
Roman Mahotskyi

Reputation: 6625

The mapDispatchToProps is a simple function which returns an object. The object's key is a name of your method and value is your actual function.

Your method should look like this:

const mapDispatchToProps = dispatch => {
   return {
     fooMethod: () => {},
     barMethod: () => {},
   };
};

connect(undefined, mapDispatchToProps)(<Your component>);

After that, you can get access to these methods via props.

Upvotes: 7

Related Questions