Skip to content

Instantly share code, notes, and snippets.

@zeroFruit
Created December 10, 2017 03:20
Show Gist options
  • Save zeroFruit/bbcd9b67f6afad96ef129e50af419659 to your computer and use it in GitHub Desktop.
Save zeroFruit/bbcd9b67f6afad96ef129e50af419659 to your computer and use it in GitHub Desktop.
React, Reducer, Saga helper
/*
Reducer Helper
*/
export function createReqeuestTypes(_base) {
let base = _base;
if (Array.isArray(base)) base = base.join('/');
const res = {};
[REQUEST, SUCCESS, FAILURE]
.forEach(type => res[type] = `${base}_${type}`);
return res;
}
export function patch(type, _patch = {}, mergeKey) {
const rt = { type, patch: _patch };
if (mergeKeys) {
rt.mergeKeys = Array.isArray(mergeKeys) ? mergeKeys : [mergeKeys];
}
return rt;
}
/*
Action Helpers
*/
export function createType(_base) {
let base = _base;
if(Array.isArray(base)) {
base = base.join('/');
}
return base;
}
export function action(type, payload = {}) {
return { type, ...payload };
}
export function* fetchEntity(entity, apiFn, ...args) {
yield put(entity.request());
try {
const result = yield call(apiFn, ...args);
yield put(entity.success(result));
} catch (error) {
yield put(entity.failure(error));
}
}
/*
Action Saga
*/
export function* initLoad() {
const _isLoaded = yield select(isLoaded);
if (!_isLoaded) {
yield call(getLoad);
}
}
export function* watchReqeustData() {
while(true) {
yield take(REQUEST_LOAD);
yield fork(initLoad);
}
}
/*
ducks
*/
const LOAD = createReqeuestTypes(['info', 'LOAD']);
const requestData = {
request: () => patch(LOAD.REQUEST, { loading: true }),
success: (data) => patch(LOAD.SUCCESS, { loading: false, loaded: true, data }),
failure: (error) => patch(LOAD.FAILURE, { loading: false, loaded: false, error });
};
const REQUEST_LOAD = createType(['info', 'REQUEST_LOAD']);
export const load = (params) => action(REQUEST_LOAD, { params });
const getLoad = fetchEntity.bind(null, requestData, client.get('/loadInfo'));
/*
Global Spinner
*/
// View
doCommentSave = (param) => {
this.props.saveComment(param);
}
// Saga
export function* watchSaveData() {
while(true) {
const { data } = yield take(REQUEST_SAVE);
yield put(showGlobalSpinner());
yield fork(saveData, data);
yield take([SAVE.SUCCESS, SAVE.FAILURE]);
yield put(reloadPost(data.postId));
yield put(hideGlobalSpinner());
}
}
251-451
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment