Skip to content

Instantly share code, notes, and snippets.

// Throttling
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.throttleTime(500)
...
// Throttling
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.throttleTime(500)
...
// Deboucing
const inputEpic = (action$) =>
action$.ofType('INPUT_CHANGED')
.debounceTime(500)
// Throttling
function* handleInput(input) {
// ...
}
function* watchInput() {
yield throttle(500, 'INPUT_CHANGED', handleInput)
}
// Debouncing
// 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)
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);
}
}
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 { takeEvery } from 'redux-saga';
import { call, put } from 'redux-saga/effects';
// Watcher
function* watchFetchData() {
yield* takeEvery('FETCH_REQUESTED', fetchData);
}
// Worker
function* fetchData(action) {
import { call, put } from 'redux-saga/effects'
export function* fetchData(action) {
try {
const data = yield call(Api.fetchUser, action.payload.url)
yield put({type: "FETCH_SUCCEEDED", data})
} catch (error) {
yield put({type: "FETCH_FAILED", error})
}
}
const pingEpic = action$ =>
action$.filter(action => action.type === 'PING')
.mapTo({ type: 'PONG' });
// later...
dispatch({ type: 'PING' });
@Calvin-Huang
Calvin-Huang / redux-action-sequences-3.js
Created September 5, 2017 21:10
Use redux-thunk to handle action sequences.
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);