salsita / prism

React / Redux action composition made simple http://salsita.github.io/prism/
495 stars 24 forks source link

How to wrap/unwrap dynamic components? #82

Closed dfedynich closed 7 years ago

dfedynich commented 7 years ago

Hello, team!

I wonder, how to manage with wrap/unwrap process, when the number of reusable components can be changed dynamically?

In you your example you assume, that we there are only two specific counters: top and bottom. But what if counters can be created/deleted dynamically? How to specify selector and wrapper in this case?

const RootComponent = () => (
  <div>
    <InstantiableConnectedCounter
      selector={state => state.topCounter} // State passed to mapStateToProps will be automatically selected using provided selector
      wrapper={type => `TopCounter.${type}`} // All the dispatched actions will be prefixed with TopCounter.
    />
    <InstantiableConnectedCounter
      selector={state => state.bottomCounter}
      wrapper={type => `BottomCounter.${type}`}
    />
  </div>
);

How should I build the reducer in the case of dynamic components?

export default buildReducer([{
  unwrapper: buildUnwrapper('Top'), // Unwraps Top prefixed actions
  handler: (state, action) => ({
    ...state,
    top: counterReducer(state.top, action)
  })
}, {
  unwrapper: buildUnwrapper('Bottom'), // Unwraps Bottom prefixed actions
  handler: (state, action) => ({
    ...state,
    bottom: counterReducer(state.bottom, action)
  })
}, {
  unwrapper: buildUnwrapper('ResetCounters'), // Direct match for ResetCounters action
  handler: (state, action) => initialState
}], initialState);

By the way, there was a similar question about this use case - #46. If the answer is similar to it, could you provide the example of the best practice how to use prsim in this case?

Dattaya commented 7 years ago

@dfedynich, take a look at @tomkis' answer to my question and an example in the next message, should be enough information for you to solve this task.

dfedynich commented 7 years ago

@Dattaya, thank you, Yaroslav, for the response and quick feedback. Your implementation to handle with dynamic components is clear. Now, I understood some of the ideas in prisma to move from the library to the set of HOC, utils and wrappers. The wise and light way in my view.