stream-saga/src/js/sagas/api-saga.js

67 lines
1.4 KiB
JavaScript
Raw Normal View History

2019-06-21 10:53:16 -04:00
import { takeEvery, call, put, all } from 'redux-saga/effects'
2019-06-19 22:37:59 -04:00
export default function* watcherSaga() {
2019-06-21 10:53:16 -04:00
yield all([
worker(),
workerHillary(),
workerTrump()
])
}
function* worker() {
2019-06-21 00:06:42 -04:00
yield takeEvery("DATA_REQUESTED", workerSaga)
2019-06-19 22:37:59 -04:00
}
function* workerSaga() {
2019-06-21 00:06:42 -04:00
try {
const payload = yield call(getData)
yield put({ type: "DATA_LOADED", payload })
} catch (e) {
yield put({ type: "API_ERRORED", payload: e })
}
2019-06-19 22:37:59 -04:00
}
2019-06-21 10:53:16 -04:00
function* workerHillary() {
yield takeEvery("DATA_TRUMP_REQUESTED", workerTrumpSaga)
}
function* workerHillarySaga() {
try {
const payload = yield call(getHillaryData)
yield put({ type: "DATA_LOADED", payload })
} catch (e) {
yield put({ type: "API_ERRORED", payload: e })
}
}
2019-06-21 00:59:25 -04:00
2019-06-21 10:53:16 -04:00
function* workerTrump() {
yield takeEvery("DATA_HILLARY_REQUESTED", workerHillarySaga)
}
function* workerTrumpSaga() {
try {
const payload = yield call(getTrumpData)
yield put({ type: "DATA_LOADED", payload })
} catch (e) {
yield put({ type: "API_ERRORED", payload: e })
}
}
function getData() {
2019-06-21 00:59:25 -04:00
return fetch("https://jsonplaceholder.typicode.com/posts").then(response =>
response.json()
)
2019-06-19 22:37:59 -04:00
}
2019-06-21 10:53:16 -04:00
function getHillaryData() {
return fetch("http://localhost:3030/api/twitter?hashtag=Hillary%20Clinton").then(res1 =>
res1.json()
)
}
function getTrumpData() {
return fetch("http://localhost:3030/api/twitter?hashtag=Donald%20Trump").then(res1 =>
res1.json()
)
}