0

If I'm using an async redux library along with reselect, is there a definitive pattern for performing a selection in mapStateToProps when the state object being "selected" depends on the completion of the async action?

I'm using the following solution, but it seems inelegant...

const mapStateToProps = (state) => {
    if (state.roles.list.length) {
        return {
            role: selectRole(state),
            permissions: selectPermissions(state)
        }
    } else {
        return {}
    }
}

class MyComponent extends React.Component {
    componentDidMount() {
        this.props.dispatch(getAllRolesAndPermissions());
    }
    ...
}

connect(mapStateToProps)(MyComponent)

How can I perform "selections" with reselect library on state that depends on async actions to populate the state?

Himmel
  • 3,629
  • 6
  • 40
  • 77
  • If your state was changed, then `mapStateToProps` will be called, then your selectors will do their job and component will be re-rendered with new props. – Denis Ivanov Sep 01 '16 at 22:02
  • I would probably not do the conditional in mapStateToProps as well, instead I would have selectors return default value. Also, you need to be really careful with shared selectors. Make sure they are caching properly, otherwise you may face big perf issues. – Denis Ivanov Sep 01 '16 at 22:06
  • Sorry, one more comment! Try to keep your state as flat as possible. I noticed you have some level of nesting here `state.roles.list`.Take a look at this library for more explanation https://github.com/paularmstrong/normalizr. – Denis Ivanov Sep 01 '16 at 22:08
  • @DenisIvanov how can I make sure that the selectors are caching properly? Also I'm not sure how else to keep metadata about a state structure besides doing something like `{isFetching: false, list: []}`. – Himmel Sep 01 '16 at 22:28
  • 2
    in general, if you see that your component re-renders when the property values are the same, that means that selector may return new instances every time. I use https://github.com/garbles/why-did-you-update, in conjuction with placing log statements in selectors. Also, you could use react-dev-tools with 'trace react updates' on to see if you re-render everything. The issue is described here: https://github.com/reactjs/reselect#sharing-selectors-with-props-across-multiple-components – Denis Ivanov Sep 01 '16 at 22:43
  • See if you could have `isFetching` as an independent key in store. From my experience dealing with heck of performance issues on large scale app, having the store as flat and as simple as possible makes it easier to deal with. – Denis Ivanov Sep 01 '16 at 22:50

0 Answers0