From df88e7261e1935da87f445f949316dc3019ab84c Mon Sep 17 00:00:00 2001 From: Rodrigo Pedroso <> Date: Wed, 19 Jun 2019 22:37:59 -0400 Subject: [PATCH] Redux-saga --- src/js/actions/index.js | 8 +------- src/js/sagas/api-saga.js | 20 ++++++++++++++++++++ src/js/store/index.js | 8 ++++++-- 3 files changed, 27 insertions(+), 9 deletions(-) create mode 100644 src/js/sagas/api-saga.js diff --git a/src/js/actions/index.js b/src/js/actions/index.js index ac839ba..e2c3c50 100644 --- a/src/js/actions/index.js +++ b/src/js/actions/index.js @@ -5,11 +5,5 @@ export function addArticle(payload) { } export function getData() { - return function(dispatch) { - return fetch("https://jsonplaceholder.typicode.com/posts") - .then(response => response.json()) - .then(json => { - dispatch({ type: "DATA_LOADED", payload: json }); - }) - } + return { type: "DATA_REQUESTED" } } diff --git a/src/js/sagas/api-saga.js b/src/js/sagas/api-saga.js new file mode 100644 index 0000000..38366bf --- /dev/null +++ b/src/js/sagas/api-saga.js @@ -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() + ) +} diff --git a/src/js/store/index.js b/src/js/store/index.js index f8cc7ce..e9e09c1 100644 --- a/src/js/store/index.js +++ b/src/js/store/index.js @@ -1,13 +1,17 @@ import { createStore, applyMiddleware, compose } from 'redux' import rootReducer from '../reducers/index' 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 store = createStore( rootReducer, - storeEnhancers(applyMiddleware(forbiddenWordsMiddleware, thunk)) + storeEnhancers(applyMiddleware(forbiddenWordsMiddleware, initialiseSagaMiddleware)) ) +initialiseSagaMiddleware.run(apiSaga) + export default store