-
-
Save anishd19/2fab9f3ae9f5ce43ea63e4d7ce2f41cc to your computer and use it in GitHub Desktop.
polling using redux-saga
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 { delay } from 'redux-saga'; | |
| import { put, take, race, call, cancel, takeEvery } from 'redux-saga/effects'; | |
| import { Upload, addJob, removeJob } from '../actions/job'; | |
| function* upload(action: Upload) { | |
| try { | |
| const { file, jobId: id } = action.payload; | |
| yield put(addJob({ id })); | |
| // polling | |
| while (true) { | |
| const { end } = yield race({ | |
| poll: call(poll, file), | |
| end: take('POLL_END') | |
| }); | |
| if (end) { | |
| yield put(removeJob({ id })); | |
| yield cancel(); | |
| } | |
| } | |
| } catch (e) { | |
| yield put({ type: 'ERROR' }); | |
| } | |
| } | |
| function* poll(file: File) { | |
| while (true) { | |
| try { | |
| const { status } = yield fetchFoo(file); | |
| if (status === 'ok') yield put({ type: 'POLL_END' }); | |
| yield call(delay, 5000); | |
| } catch (e) { | |
| yield put({ type: 'POLL_ERROR' }); | |
| } | |
| } | |
| } | |
| export function* uploadingProcess() { | |
| yield takeEvery('UPLOAD', upload); // don't use takeLatest for parallel processing | |
| } | |
| export function* rootSaga() { | |
| yield all([fork(uploadingProcess)]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment