aweary / react-copy-write

✍️ Immutable state with a mutable API
MIT License
1.79k stars 54 forks source link

Question about apply() #50

Closed hnordt closed 6 years ago

hnordt commented 6 years ago

I was reading the source code of the project to learn more. The source code is just awesome, it was definitely written by an artisan.

There is only one part that I didn't understand:

return children.apply(null, state);

https://github.com/aweary/react-copy-write/blob/master/src/index.js#L101

Could you explain why did you use children.apply(null, state) instead of children(state)?

Thank you muchly!

aweary commented 6 years ago

Thanks 🙂

state is stored internally as an array. Since you can provide an array of selectors to select you might have multiple selections of state for any given component.

[state1, state2, state3]

With the current API, we don't pass that array directly to the render prop, like:

<Consumer select={[selector1, selector2, selector3]}>
  {([state1, state2, state3]) => {
    // ...
  })

Because that can get annoying when you only have one selector. Instead, each selection is passed as a separate argument

<Consumer select={[selector1, selector2, selector3]}>
  {(state1, state2, state3) => {
    // ...
  })

So what apply does is take that array of state and call children with each item as an additional argument.

Hope that makes sense!

hnordt commented 6 years ago

Thanks @aweary. That's a clever alternative to (...args) => fn(...args).