Skip to content

Instantly share code, notes, and snippets.

@Calvin-Huang
Last active September 6, 2017 01:00
Show Gist options
  • Save Calvin-Huang/e87d42292e0a0688556ccfcdef45a22d to your computer and use it in GitHub Desktop.
Save Calvin-Huang/e87d42292e0a0688556ccfcdef45a22d to your computer and use it in GitHub Desktop.
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);
}
}
function* fetchData(action) {
try {
const data = yield call(fetchAPI, action.payload.url);
yield put({type: 'FETCH_SUCCEEDED', data});
} catch (error) {
yield put({type: 'FETCH_FAILED', error});
}
}
// Wrap axios
function fetchAPI(url) {
const source = CancelToken.source();
const request = axios.get(url);
request[CANCEL] = () => source.cancel();
return request;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment