1

I'm learning redux and in this piece of code section there is a continuous function to pass the arguments. I couldn't understand the logic behinds that because i'm the PHP developer originally and it's unusual there. would you please explain and simplify that for me?

Here is my selector:

export const personBugs = userId => createSelector(
    state => state.entities.bugs,
    bugs => bugs.filter(bug => bug.userId === userId )
)

And here is my dispatch:

console.log(bugsActions.personBugs(1)(store.getState()));
rahman j89
  • 59
  • 8
  • 1
    It's called "currying", not "continuous function". – Rickard Elimää Jan 27 '22 at 08:01
  • Does this answer your question? [Functions that return a function](https://stackoverflow.com/questions/7629891/functions-that-return-a-function) – evolutionxbox Jan 27 '22 at 08:14
  • 1
    Be careful with most functional features in JavaScript. JavaScript lacks [tail call optimization](https://stackoverflow.com/q/310974/402322), which makes any kind of recursion quite dangerous. – ceving Jan 27 '22 at 08:59
  • @ceving for some reason, only iOS and Safari do https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation) – evolutionxbox Jan 27 '22 at 13:10

1 Answers1

2

It's called a curry function or currying, this is when you want to provide one argument and at a later time provide another argument.

I am not sure why a selector is on your actions object but I'm sure that is a mistake. A selector is usually used in components to get data that the component needs but can also be used in middleware to get state info.

Here is an example of how a selector can be used in a component:

const PersonBugs = React.memo(function PersonBugs({
  personId,
}) {
  //here is a way to use the curry
  const bugs = useSelector(personBugs(personId));
  //if this wasn't a curry you have to do
  // const bugs = useSelector((state) =>
  //   personBugs(personId, state)
  // );
  //you could also not memoize the selector if you needed to
});

More information about selectors can be found here

HMR
  • 37,593
  • 24
  • 91
  • 160
  • The selector is not in action object. I call it from there. My code is running well but it's the training code and may be different from the real code. Thanks for your answer, that's useful. – rahman j89 Jan 28 '22 at 03:08