Created
April 20, 2017 20:06
-
-
Save dminuoso/7dc8e98fb52b22fc37a2865556a1e7b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { put, call, race, fork, take, cancel, select, delay, cancelled } from 'redux-saga/effects'; | |
import { makeSelectMask } from './selectors'; | |
import { createRequestCreators } from './actions'; | |
function* fetchEntity(entity, apiFn, opts, id, url) { | |
try { | |
yield put(entity.request(id)); | |
const { response, error } = yield call(apiFn, url || id); | |
if (response) { | |
yield put(entity.success(id, response)); | |
} else { | |
if (opts.handleError) { | |
opts.handleError(); | |
} | |
yield put(entity.failure(id, error)); | |
} | |
} finally { | |
if (yield cancelled()) { | |
yield put(entity.cancel()); | |
} | |
} | |
} | |
export const searchWatchChange = (searchConstants) => ( | |
function* () { // eslint-disable-line func-names | |
for (;;) { | |
const { setField } = yield race({ | |
setField: take(searchConstants.SET_FIELD), | |
setPage: take(searchConstants.SET_PAGE), | |
setPageSize: take(searchConstants.SET_PAGE_SIZE), | |
}); | |
if (setField) { | |
yield put({ type: searchConstants.START_SEARCH, wait: 250 }); | |
} else { | |
yield put({ type: searchConstants.START_SEARCH }); | |
} | |
} | |
} | |
); | |
export const searchWatchStart = (searchConstants, selectSearch, apiFn, handleError) => { | |
const searchCreators = createRequestCreators(searchConstants.FETCH_STATUS); | |
const loadResults = fetchEntity.bind(null, searchCreators, apiFn, { handleError }); | |
const selectMask = makeSelectMask(selectSearch); | |
return function* () { // eslint-disable-line func-names | |
let lastTask; | |
for (;;) { | |
const { wait } = yield take(searchConstants.START_SEARCH); | |
if (lastTask) { | |
yield cancel(lastTask); | |
} | |
const searchMask = yield select(selectMask); | |
lastTask = yield fork(function* () { // eslint-disable-line func-names | |
if (wait) { | |
yield call(delay, wait); | |
} | |
yield call(loadResults, searchMask); | |
}); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment