Last active
September 6, 2017 01:00
-
-
Save Calvin-Huang/e87d42292e0a0688556ccfcdef45a22d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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