Skip to content

Add a generic reducer factory automatically handling async-actions - createAsyncReducer #88

@lajtmaN

Description

@lajtmaN

Issuehunt badges

Is your feature request related to a problem?

It would be awesome to be able to build reducer factories which are based on async actions, that can in a generic way handle the payloads of that async action.

Who does this impact? Who is this for?

All users - as an example you could create an async action and create a reducer with a simple one liner for simple reducers like loading and error.

Example

The following example utilizes that all async failure actions return an Error object.

export const fetchCurrentUserActions = createAsyncAction(...)<void, FetchCurrentUserDetailsResponse, Error>();


export const currentUserReducer = combineReducers<CurrentUserState>({
  loading: createLoadingReducer(fetchCurrentUserActions), // <---- Nice one line reducer
  error: createErrorReducer(fetchCurrentUserActions), // <---- Nice one line reducer
  ....
});

export const createErrorReducer = <TSuccess>(
  asyncAction: AsyncActionBuilder<any, any, any, any, TSuccess, Error>
): Reducer<ErrorState> => 
  (state = null, action: ActionType<typeof asyncAction>) => {
    switch (action.type) {
      case getType(asyncAction.failure):
        return action.payload; // <---- action is not narrowed after getType(), thus .payload doesn't exist on action or isn't of type Error as expected
      case getType(asyncAction.success):
        return null;
      default:
        return state;
    }
  };

My createLoadingReducer does not care about any payloads thus my reducer function just takes an AnyAction


IssueHunt Summary

Backers (Total: $115.00)

Become a backer now!

Or submit a pull request to get the deposits!

Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Metadata

Metadata

Assignees

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions