In my Redux store I have a list of notes. I wish to
- Filter out the notes that are created by me
- sort those notes by created date / title / etc.
I would 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
I am using this function for my purposes, so you can provide this function right into Array.sort and provide any field alias you need. In my opinion this is good for maintaining and also, you dont need to provide an array to your sorting fucntion.