React-redux: Correct way of dispatching an action from mapDispatchToProps

Created on 13 Oct 2016  路  2Comments  路  Source: reduxjs/react-redux

Hello,

As I read in some other issue I can return a function from mapDispatchToProps, which will be called each time (own)prop changes.

I want to trigger an action when prop changes.

The current code I have (shortened a bit):

export const mapDispatchToProps = (initialDispatch, initialOwnProps) => {
    const onRatingPropsChange = () => {
        initialDispatch(clearAction());
    };

    const loadMore = () => {
        initialDispatch(loadMoreAction());
    };

    return (dispatch, ownProps) => {
        onRatingPropsChange();
        return {
            loadMore: loadMore,
        };
    };
};

This works fine. If a prop of connected component changes - data is cleared. Connected component can call props.loadMore() to load more data.

But when clearAction is dispatched on the browser console I get:

warning.js:36 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

How to fix that? How should I do this properly?

Most helpful comment

Don't try to dispatch actions inside mapStateToProps. This is not allowed. Perhaps we could do a better job in the docs and error messages to stress this.

All 2 comments

I think the best place for this question is probably stack overflow.

However, mapDispatchToProps intent and responsibility is to pass dispatch to your functions that you are wrapping.

The functionality that you are describing is probably best in componentWillRecieveProps, you would use the newProps coming in to do your checks and then invoke the functions that are wrapped with mapDispatchToProps

Hope this helps.

Don't try to dispatch actions inside mapStateToProps. This is not allowed. Perhaps we could do a better job in the docs and error messages to stress this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DillonGray picture DillonGray  路  3Comments

fuchsberger picture fuchsberger  路  3Comments

nainardev picture nainardev  路  3Comments

a-koka picture a-koka  路  3Comments

kissyRui picture kissyRui  路  3Comments