Skip to content

Consider creating curried selectors with data-last args #490

Open

Description

@malyzeli

When using createSelector factory, we receive selector function accepting state first and searchKey last.
(* I don't know how searchKey arg is called in sources)

This gets cumbersome quickly, having to repeat still the same boilerplate code as an input to useSelector.

Look at the example code from the documentation:

const authors = createSelector(orm.Author);
const authorBooks = createSelector(orm.Author.books);

function AuthorProfile(props) {
  const author = useSelector(state => authors(state, props.authorId));
  const books = useSelector(state => authorBooks(state, props.authorId));
  return (/*...*/);
};

We have to repeat the pattern of STATE => selector(STATE, searchKey) all over!

Creating curried selector accepting args in reversed order can provide cleaner API, achieving the same results with less code and even support better memoization or various functional composition...

const selector = (searchKey) => (state) => result;

Having this, now we could simplify the code above to the following:

function AuthorProfile(props) {
  const author = useSelector(authors(props.authorId));
  const books = useSelector(authorBooks(props.authorId));
  return (/*...*/);
};

And you can also use it to create something like "prepared statement" selectors to pass around and call later.

const profileSelector = authors(currentUserId);

function PersonalProfile() {
  const profile = useSelector(profileSelector);
  return (/*...*/);
};

Of course we can create such kind of selectors in user code pretty easily...

function createCurriedSelector(...args) {
  const selector = createSelector(...args);
  return (searchKey) => (state) => selector(state, searchKey);
}

But I think this might be included in the library by default, since I believe it noticeably simplifies the usage.

const authors = createCurriedSelector(orm.Author);
const authorBooks = createCurriedSelector(orm.Author.books);

function AuthorProfile(props) {
  const author = useSelector(authors(props.authorId));
  const books = useSelector(authorBooks(props.authorId));
  return (/*...*/);
};

If it won't make it directly into the sources, I suggest putting example of createCurriedSelector at least as a tip into the documentation.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions