6
votes

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 render the Container component and click the button, only '#1' is being displayed in the console. So the 'thunk' doesn't get executed.

When I explicitly dispatch actionCreator(), it does work:

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

The Redux docs says this about mapDispatchToProps:

If an object is passed, each function inside it will be assumed to be a Redux action creator

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

Update

When using bindActionCreators() from redux it does work:

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

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

2

2 Answers

7
votes

In your mapDispatchToProps, you are overriding the dispatch function by making it an argument of the function. Because you are doing the dispatch => {function}, the dispatch inside the function now refers to the argument you pass to the function – but you don't pass any argument to it.

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

Change it to this, and it should work:

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

That way, when you call callback(), the dispatch refers to the passed dispatch function by mapDispatchToProps, and the action gets dispatched.

1
votes

It's because your actionCreator function returns a new function when it gets called. Remove the return in actionCreator will make it work.