Shawn Matthews
Shawn Matthews

Reputation: 1832

Using Reselect in mapState to add together selector values

Feel like I'm missing something simple here.

If I have the following selectors (see code). Using Reselect how can I combine them together to make a new selector? I'm looking to do something like this...

export const mapState = (state, ownProps) => {
  return {
    //SELECTORS!
    sub1: selector(state, 'sub1') || 0,
    sub2: selector(state, 'sub2') || 0,
    totalSelector: createSelector(sub1, sub2, (sub1, sub2) => ({total: sub1 + sub2}))
  };
};

Does this need to be done outside of mapState? Currently sub1 and sub2 in 6th line are undefined.

Upvotes: 0

Views: 115

Answers (1)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36199

Yes, they need to be defined before an object is created, like:

export const mapState = (state, ownProps) => {
  const sub1 = selector(state, 'sub1') || 0;
  const sub2 = selector(state, 'sub2') || 0;
  return {
    //SELECTORS!
    sub1,
    sub2,
    totalSelector: createSelector(sub1, sub2, (sub1, sub2) => ({total: sub1 + sub2}))
  };
};

The problem is that in your mapState you pass undefined to createSelector function because sub1 and sub2 is not yet created. You need to create them before the returned object is constructed.

Upvotes: 1

Related Questions