M
M
Maxim Nikulin2016-04-16 16:40:15
JavaScript
Maxim Nikulin, 2016-04-16 16:40:15

Is it possible to filter and sort data in a React container using Reselect and Redux?

Hello. There was a question with reselect for redux . I’ll make a reservation right away that I solved the problem by creating another field in the reducer, which stored the sorted / filtered array, depending on the actions.
However, I think that both sorting and filtering are separate UI issues. Accordingly, I would like to implement the same functions, but in a container (Smart component).
Initial state of the root reducer:

let initialState = {
  persons:[],
  active:0,
  loading:false,
  filter:"",
  field:"name"
}

1. First, using reselect, I created two selectors that, when the corresponding fields changed, called the necessary functions:
let getPersons = (state) => state.persons
let getFilter = (state) => state.filter
let getField = (state) => state.field

let filterData = createSelector(
  getPersons,
  getFilter,
  (persons,filter) => {
    return persons.filter( p =>{
      console.log("FILTER");
      return p.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1
    })
  },
)

let sortData = createSelector(
  getPersons,
  getField,
  (persons,field) =>  {
    console.log("SORT");
    let sortarr = persons.slice(0);
    return sortarr.sort((a , b) => {
      if (a[field] > b[field])  return  -1
      if (a[field] < b[field])  return  1
      return 0
  })
})

2. Actually, sortData now returns a sorted array by the last field and, importantly, stores its value, which helps us avoid unnecessary sorting calls.
Similar to fielterData
3. You need to implement filtering the latest sorted data and sorting the latest filtered data
code link:
https://github.com/maximusnikulin

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
comerc, 2017-02-11
@comerc

This link is not to the code, but to the account. If I understand correctly, the question is how to marry two selectors. Did you manage to win?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question