Redux Selectors – Filter and sort one or more selectors?

In my Redux store I have a list of notes. I wish to

  1. Filter out the notes that are created by me
  2. sort those notes by created date / title / etc.

I would also like to separate logic for filtering and sorting into own functions to make the code more easy to maintain.

I have read the tutorial on redux-reselect and have come up with the below structure.

import { createSelector } from 'reselect';

const sortNotesBy = ({notes, sortBy}) => {
  return notes.sort((a, b) => {
    if (sortBy === TITLE) {
      //dueDate date - createdAt
      return a.dueDate > b.dueDate ? -1 : 1
    }
    else if (sortBy === CREATED_DATE) {
      //createdAt
      return a.createdAt > b.createdAt ? -1 : 1
    }
  })
}

const getMyNotes = ({notes, uid}) => {
  return notes.filter(note => note.author === uid)
}

const sortBy = props.sortBy // set by mapStateToProps
const uid = props.uid // set by mapStateToProps
const notesSelector = state => state.notes;

// Filter out my notes
export const myNotes = createSelector([notesSelector], notes => {
  return getMyNotes({notes, uid})
});

// Sort my notes
export const sortedNotes = createSelector([myNotes], notes => {
  return sortNotesBy({notes, sortBy})
});

Is the above approach of "stacking" selectors a good approach to accomplish code separation, or might there be any issues with this approach?

Kind regards /K



Read more here: https://stackoverflow.com/questions/64952753/redux-selectors-filter-and-sort-one-or-more-selectors

Content Attribution

This content was originally published by Kermit at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: