Skip to content

Instantly share code, notes, and snippets.

@jiayihu
Last active September 20, 2019 13:10
Show Gist options
  • Save jiayihu/811f2dc704d6ce6308d679a987348b20 to your computer and use it in GitHub Desktop.
Save jiayihu/811f2dc704d6ce6308d679a987348b20 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);
},
};
}
@jiayihu
Copy link
Author

jiayihu commented Feb 19, 2017

Example of usage:

export const addInvoice = createAction('ADD_INVOICE', {
  request: (invoice) => ({ invoice }),
  success: (invoice, result) => ({ invoice, result }),
});

// Dispatching
store.dispatch(addInvoice.request({ id: 1 }));

@ladas-larry
Copy link

ladas-larry commented Jun 4, 2018

This is awesome!! Have you tried to create PR in redux-saga repo?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment