Home > OS >  Calling 2 curried functions onChange
Calling 2 curried functions onChange

Time:08-22

I have a checkbox which calls a curried function and works fine when changing the checkstate as below

const FirstCurriedFunc = (id) => () => {
  //does something
}

return (
   <input type="checkbox" checked={true} onChange={FirstCurriedFunc(id)} />
)

However when I try to call two curried Functions onChange neither function executes as expected even though they both work when called individually as above.

const SecondCurriedFunc = (id) => () => {
  //does something
}

const BothCurriedFuncs = (id) => () => {
  FirstCurriedFunc(id);
  SecondCurriedFunc(id);
}

return (
    <input type="checkbox" onChange={BothCurriedFuncs(id)} />  // neither function executes
);

Can anyone explain why this is/provide a way to call both functions onChange?

CodePudding user response:

You have to actually invoke both functions in BothCurriedFuncs:

const BothCurriedFuncs = (id) => () => {
    FirstCurriedFunc(id)();
    SecondCurriedFunc(id)();
}

or, maybe cleaner, use a helper function to create a composition:

let compose = (...fns) => () => fns.reduceRight((x, f) => f(x), null)


const BothCurriedFuncs = (id) => compose(SecondCurriedFunc(id), FirstCurriedFunc(id))
  • Related