React Redux connect () with Redux thunk

I have a problem when using Redux thunk with the connect() method from react-redux . I have the following code:

 function Component(props) { return ( <button onClick={props.callback}>Click here</button> ); } function actionCreator() { console.log('#1'); return dispatch => console.log('#2'); // = thunk } const mapDispatchToProps = dispatch => ({ callback: actionCreator }); export const Container = connect(null, mapDispatchToProps)(Component); 

When I create the Container component and click the button, only "# 1" is displayed in the console. Thus, thunk is not executed.

When I explicitly dispatch actionCreator() , it works:

 const mapDispatchToProps = dispatch => ({ callback: dispatch => dispatch(actionCreator()) }); 

Redux docs talk about this: mapDispatchToProps :

If an object is passed, each function within it will be considered the creator of the Redux action

So why mapDispatchToProps not dispatch() my actionCreator() ? I'm new to React, so maybe I don't get it right?

Update

When using bindActionCreators() from redux, it works:

 const mapDispatchToProps = dispatch => { return bindActionCreators({ callback: actionCreator }, dispatch); }; 

Is this the right way to bind actioncreators with connect() ?

+6
source share
2 answers

In mapDispatchToProps you override the dispatch function, making it an argument to the function. Since you are doing dispatch => {function} , sending inside a function now refers to the argument that you pass to the function, but you do not pass any arguments to it.

 callback: dispatch => dispatch(actionCreator()) // ^ overrides ^ 

Change it to this and it should work:

 const mapDispatchToProps = dispatch => ({ callback: () => dispatch(actionCreator()) }); 

Thus, when you call callback() , dispatch refers to the dispatch function passed to mapDispatchToProps , and the action is dispatched.

+6
source

This is because your actionCreator function returns a new function when called. Remove return in actionCreator to make it work.

0
source

All Articles