Skip to content

Instantly share code, notes, and snippets.

@Calvin-Huang
Last active September 6, 2017 01:06
Show Gist options
  • Save Calvin-Huang/909d1673e83b40bccbf72f39d1313fad to your computer and use it in GitHub Desktop.
Save Calvin-Huang/909d1673e83b40bccbf72f39d1313fad to your computer and use it in GitHub Desktop.
// 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)
.map(data => ({ type: 'FETCH_SUCCEEDED', data }))
.catch(error => Observable.of({ type: 'FETCH_FAILED', error }))
.takeUntil({ type: 'CANCEL_FETCH' });
})
// Or use axios
// import axios from 'axios';
// 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 axios.get(action.payload.url)
// .map(data => ({ type: 'FETCH_SUCCEEDED', data }))
// .catch(error => Observable.of({ type: 'FETCH_FAILED', error }))
// .takeUntil(action$.ofType('CANCEL_FETCH')));
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment