Skip to content

Instantly share code, notes, and snippets.

@ladas-larry
Forked from jiayihu/actionCreator.ts
Created July 9, 2019 07:29
Show Gist options
  • Save ladas-larry/e7933ece9c32c62d7f760fec90a813e2 to your computer and use it in GitHub Desktop.
Save ladas-larry/e7933ece9c32c62d7f760fec90a813e2 to your computer and use it in GitHub Desktop.
Minimal action creator factory for redux-observable and redux-saga
import { IAction } from '../types/redux.types';
import { actionTypes as errorTypes, showError } from './errors.actions';
interface IPayloadCreators {
request(...args: any[]): any;
success(...args: any[]): any;
failure?(errorMsg: string): any;
}
interface IActionCreator {
types: { request: string; success: string; failure: string; };
request(...args: any[]): IAction;
success(...args: any[]): IAction;
failure(errorMsg: string): IAction;
}
const defaultPayload = (args) => args;
export default function createAction(type: string, payloadCreators: IPayloadCreators): IActionCreator {
const requestType = `${type}_REQUEST`;
const successType = `${type}_SUCCESS`;
const failureType = payloadCreators.failure ? `${type}_FAILURE` : errorTypes.SHOW_ERROR;
return {
types: { request: requestType, success: successType, failure: failureType },
request(...args) {
return {
type: requestType,
payload: payloadCreators.request ? payloadCreators.request(...args) : defaultPayload(args),
};
},
success(...args) {
return {
type: successType,
payload: payloadCreators.success ? payloadCreators.success(...args) : defaultPayload(args),
};
},
failure(errorMsg: string) {
if (payloadCreators.failure) {
return {
type: failureType,
payload: payloadCreators.failure(errorMsg),
};
}
return showError(errorMsg);
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment