Last active
April 2, 2020 07:02
-
-
Save ellismarkf/d2824ea9d668c4c00af5112633f91a1d to your computer and use it in GitHub Desktop.
Polling with redux-saga
This file contains 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 { call, put, race, fork, take } from 'redux-saga/effects' | |
function delay(duration) { | |
const promise = new Promise(resolve => { | |
setTimeout(() => resolve(true), duration) | |
}); | |
return promise; | |
} | |
// Fetch data every 20 seconds | |
function* pollData(url) { | |
try { | |
yield call(delay, 20000); | |
const response = yield call(get, url) | |
// TODO: pass condition as argument to pollData instead of calculating it in the function | |
const condition = 'use-response-to-calculate-if-condition-is-met' | |
// TODO: pass action type information as argument to make polling function more flexible | |
if (condition) yield put({type: 'POLL_CONDITION_MET', ...response}) | |
else yield put({ type: 'POLL_FOR_X', url }) | |
} catch (error) { | |
yield put({ type: 'POLLING_ERROR', error }) | |
return; | |
} | |
} | |
// Wait for polling action, then fire another request | |
// Cancel polling once condition is met | |
function* watchPollData() { | |
while (true) { | |
const { url } = yield take('POLL_FOR_X') | |
yield race([ | |
fork(pollData, url), | |
take('POLL_CONDITION_MET') | |
]); | |
} | |
} | |
// Daemonize tasks in parallel | |
export default function* root() { | |
yield [ | |
watchPollData() | |
// other watchers here | |
]; | |
} | |
function get(endpoint, tenant) { | |
return fetch(endpoint) | |
.then(res => res.json()) | |
.then(json => json) | |
} |
Hi, I believe your code has to be changed to either use call
or to change cancel polling management.
yield race([
fork(pollData, url),
take('POLL_CONDITION_MET')
]);
Fork immediately resolves, so "POLL_CONDITION_MET" is doing nothing - the saga is being called and forked and we go back up in the loop to wait for take POLL_FOR_X.
https://codepen.io/wjaszczak/pen/pxgVEX?editors=1111 - fork version
https://codepen.io/wjaszczak/pen/xyZjYq?editors=1111 - delegated cancel handling, many active 'polling' methods.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks.