Skip to content

Instantly share code, notes, and snippets.

import { takeEvery } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
// Watcher
function* watchFetchData() {
yield* takeEvery('FETCH_REQUESTED', fetchData);
}
// Worker
function* fetchData(action) {
import 'rxjs';
import { combineEpics } from 'redux-observable';
// Use RxJS ajax
const fetchEpic = (action$) =>
action$.ofType('FETCH_REQUESTED')
.mergeMap(action => Observable.ajax.get(action.payload.url))
.map(data => ({ type: 'FETCH_SUCCEEDED', data }))
.catch(error => Observable.of({ type: 'FETCH_FAILED', error }));
import axios, { CancelToken } from 'axios';
import { CANCEL } from 'redux-saga';
function* watchFetchData() {
while (take('FETCH_REQUESTED')) {
const fetchTask = yield fork(fetchData);
yield take('CANCEL_FETCH');
yield cancel(fetchTask);
}
}
// Use RxJS ajax
const fetchEpic = (action$) =>
action$.ofType('FETCH_REQUESTED')
.mergeMap(action => {
// We want to cancel only the AJAX request, not stop the Epic from listening for any future actions.
// https://github.com/redux-observable/redux-observable/blob/master/docs/recipes/Cancellation.md
return Observable
.ajax
.get(action.payload.url)
// Throttling
function* handleInput(input) {
// ...
}
function* watchInput() {
yield throttle(500, 'INPUT_CHANGED', handleInput)
}
// Debouncing
// Throttling
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.throttleTime(500)
...
// Deboucing
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.debounceTime(500)
// Throttling
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.throttleTime(500)
...
// Deboucing
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.debounceTime(500)
...
// Retry 5 times without waiting
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.retry(5)
...
// Retry 5 times with waiting for 2 seconds
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.retryWhen(function(errors) {
// Throttling
function* handleInput(input) {
// ...
}
function* watchInput() {
yield throttle(500, 'INPUT_CHANGED', handleInput)
}