dphilipson / typescript-fsa-reducers

Fluent syntax for defining typesafe reducers on top of typescript-fsa.
MIT License
220 stars 16 forks source link

Add .getActionCreatorsUsedInCases() method #29

Closed myrjola closed 5 years ago

myrjola commented 5 years ago

Returns an array of the action creators that are used in the reducer chain. This list is useful, e.g., when you want to reset the state in another reducer when any of the actions affecting the state in the current reducer are dispatched.

const userAccountReducer = reducerWithInitialState(USER_ACCOUNT_INITIAL_STATE)
    .case(signIn, signInHandler)
    .case(signOut, signOutHandler);

const userAccountModifiers = userAccountReducer.getActionCreatorsUsedInCases();

// Reset user data when the user account changes.
const userDataReducer = reducerWithInitialState(USER_DATA_INITIAL_STATE)
    .cases(userAccountModifiers, state => USER_DATA_INITIAL_STATE);
dphilipson commented 5 years ago

Thank you very much for the contribution! I especially appreciate the added tests and documentation.

However, I'm not convinced this is something that's good to support because it creates couplings between different parts of a codebase that aren't obvious. Here are some potential concerns if I had code like the above:

I'm open to hearing your thoughts. Does that make sense?

myrjola commented 5 years ago

Thanks for your thorough comments. I agree with all your points and will abandon this PR.

In my case, I was worried that the developer would forget to add the newly created action to the reducer that should reset its state when the new action is dispatched. At first sight, it seemed easiest to just extract all the actions used in a reducer with something like the proposed getActionCreatorsUsedInCases.

After reconsidering my options, I realized that I can move the userDataReducer out from Redux into a React component's internal state. Thus, that components just needs to listen to changes to the user account state to know when the internal state should be reset.