Terry
Terry

Reputation: 1701

Using createSelector with useSelector and a selector from another file whats the correct syntax?

I have a selector setup in my reducer file, and in my react file I want to use useReducer and createSelector to call that selector only when part of the state (state.data) changes

// Selector in reducer.js

const getScore = (state = initialState) => 
  Object.values(state.data).reduce(
    (score, { status }) =>
      status === "accepted" ? score + 1 : 
      status === "rejected" ? score + 10 : 
      score, 0
  );

// Call from reactComponent.js

const score = useSelector(({ rejectionState }) => getScore(rejectionState));

What should the syntax for createSelector be and the changes to the syntax for useSelector ?

Upvotes: 1

Views: 2219

Answers (1)

Linda Paiste
Linda Paiste

Reputation: 42298

I'm not sure what's going on with rejectionState here, but I'm assuming that the data located at state.rejectionState.data rather than state.data.

You want one function which selects the data from the store, and one function which maps the data to a score. Then you use createSelector to combine the two. You can define those functions separately as variables or write them directly inside createSelector.

const {createSelector} = Reselect;

const dataSelector = (state) => state.rejectionState.data;

const getScore = (data = {}) =>
  Object.values(data).reduce(
    (score, { status }) =>
      status === "accepted"
        ? score + 1
        : status === "rejected"
        ? score + 10
        : score,
    0
  );

const scoreSelector = createSelector(dataSelector, getScore);

let exampleState = {
  rejectionState: {
    data: {
      someKey: {
        status: "accepted"
      },
      otherKey: {
        status: "rejected"
      }
    }
  }
};

console.log( "exampleState score is:" )
console.log( scoreSelector(exampleState) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/reselect/3.0.1/reselect.js"></script>

Upvotes: 1

Related Questions