Redux-saga

This commit is contained in:
Rodrigo Pedroso 2019-06-19 22:37:59 -04:00
commit df88e7261e
3 changed files with 27 additions and 9 deletions

View file

@ -5,11 +5,5 @@ export function addArticle(payload) {
} }
export function getData() { export function getData() {
return function(dispatch) { return { type: "DATA_REQUESTED" }
return fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(json => {
dispatch({ type: "DATA_LOADED", payload: json });
})
}
} }

20
src/js/sagas/api-saga.js Normal file
View file

@ -0,0 +1,20 @@
import { takeEvery, call, put } from "redux-saga/effects"
export default function* watcherSaga() {
yield takeEvery("DATA_REQUESTED", workerSaga)
}
function* workerSaga() {
try {
const payload = yield call(getData)
yield put({ type: "DATA_LOADED", payload })
} catch (e) {
yield put({ type: "API_ERRORED", payload: e })
}
}
function getData() {
return fetch("https://jsonplaceholder.typicode.com/posts").then(response =>
response.json()
)
}

View file

@ -1,13 +1,17 @@
import { createStore, applyMiddleware, compose } from 'redux' import { createStore, applyMiddleware, compose } from 'redux'
import rootReducer from '../reducers/index' import rootReducer from '../reducers/index'
import { forbiddenWordsMiddleware } from '../middleware' import { forbiddenWordsMiddleware } from '../middleware'
import thunk from 'redux-thunk' import createSagaMiddleware from "redux-saga"
import apiSaga from "../sagas/api-saga"
const initialiseSagaMiddleware = createSagaMiddleware()
const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
const store = createStore( const store = createStore(
rootReducer, rootReducer,
storeEnhancers(applyMiddleware(forbiddenWordsMiddleware, thunk)) storeEnhancers(applyMiddleware(forbiddenWordsMiddleware, initialiseSagaMiddleware))
) )
initialiseSagaMiddleware.run(apiSaga)
export default store export default store