Skip to content

Instantly share code, notes, and snippets.

@bolutife-lawrence
Last active August 24, 2018 02:07
Show Gist options
  • Save bolutife-lawrence/c6ac6c845a39c36e1311aaa1092b62fd to your computer and use it in GitHub Desktop.
Save bolutife-lawrence/c6ac6c845a39c36e1311aaa1092b62fd to your computer and use it in GitHub Desktop.
Create a reusable redux-saga for HTTP requests.
import { call } from 'redux-saga/effects';
const requireParam = (msg) => {
throw new Error(msg);
};
function* dumbScenarioHandler() {
yield;
}
const createHTTPRequestSaga = (params = {}) => {
const {
name = 'saga',
request = requireParam('`request must be a function that returns a promise.`'),
onSuccess = dumbScenarioHandler,
onError = dumbScenarioHandler,
onFatality = dumbScenarioHandler,
} = params;
function* fn(action) {
try {
const { response, error } = yield call(request, action);
if (response) {
yield call(onSuccess, response);
} else if (error) {
yield call(onError, error);
}
} catch (fatalError) {
yield call(onFatality, fatalError);
}
}
Object.defineProperty(fn, 'name', { writable: true, configurable: false });
fn.name = name;
return fn;
};
/**
*
* Usage
*
**/
const requestSomethingSaga = createHTTPRequestSaga({
name: 'requestSomethingSaga',
request: API.requestSomething, // function that returns a promise.
* onSuccess(response) {
yield put(actions.requestSucceeded(response));
},
* onError(error) {
yield put(actions.requestFailed(error));
},
* onFatality(fatalError) {
yield put(actions.requestFailed(fatalError));
},
});
/**
* Root saga manages watcher(s) lifecycle.
*/
export default function* rootSaga() {
yield all([
takeLatest(actionTypes.REQUEST_SOMETHING, requestSomethingSaga),
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment