简体   繁体   中英

Minimize parameters for createSelector in reselect Reactjs

I am using reselect in my ReactJs code. Here is the code snippet. Due to large file, i am ommitting out unnecessary code from it.

import { createSelector } from 'reselect';

const todoSelector = state => state.todo.todos;
const searchTermSelector = state => state.todo.searchTerm;
const searchViewSelector = state => state.todo.userView

export const filteredTodos = createSelector(
  [todoSelector, searchTermSelector, searchViewSelector],
  (todos, searchTerm, searchView) => {
    return todos.filter(todo => todo.title.match(new RegExp(searchTerm, 'i')));
  }
);

As you can notice the paramters for createSelector . As we know createSelector expects 2 arguments: an array of input selector(s) as the 1st argument and a function as the 2nd argument

In this case, array of input selectors is 3. ( [todoSelector, searchTermSelector, searchViewSelector] )

But in my actual code, array of input selectors are 9. I need to reduce the count from 9 to less than 4 due to sonar issues.

How can i minimize the array of input selectors and still make it work as expected. I search a lot online but i didnt find any ifno related to it. Please any suggestions?

If you want to reduce the number of arguments per selector functions, you can separate logic into multiple pieces and use createSelector function result as an argument for another createSelector function. Something like this:

const todoSelector = state => state.todo.todos;
const searchTermSelector = state => state.todo.searchTerm;
const searchViewSelector = state => state.todo.userView

export const filteredTodosByTerm = createSelector(
  [todoSelector, searchTermSelector],
  (todos, searchTerm) => {
    return todos.filter(todo => todo.title.match(new RegExp(searchTerm, 'i')));
  }
);

export const filteredTodosByView = createSelector(
  [filteredTodosByTerm, searchViewSelector],
  (todos, searchView) => {
    return todos.filter(todo => todo.title.match(new RegExp(searchView, 'i')));
  }
);
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM