Created
March 13, 2018 17:06
-
-
Save herbowicz/8f1eaacc201444f6e70bc817dcf7bc06 to your computer and use it in GitHub Desktop.
redux-thunk vs. redux-saga
This file contains 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 { call, put, takeEvery } from 'redux-saga/effects'; | |
import { | |
API_BUTTON_CLICK, | |
API_BUTTON_CLICK_SUCCESS, | |
API_BUTTON_CLICK_ERROR, | |
} from './actions/consts'; | |
import { getDataFromAPI } from './api'; | |
export function* apiSideEffect(action) { | |
try { | |
const data = yield call(getDataFromAPI); | |
yield put({ type: API_BUTTON_CLICK_SUCCESS, payload: data }); | |
} catch (e) { | |
yield put({ type: API_BUTTON_CLICK_ERROR, payload: e.message }); | |
} | |
} | |
// the 'watcher' - on every 'API_BUTTON_CLICK' action, run our side effect | |
export function* apiSaga() { | |
yield takeEvery(API_BUTTON_CLICK, apiSideEffect); | |
} |
This file contains 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 { | |
API_BUTTON_CLICK, | |
API_BUTTON_CLICK_SUCCESS, | |
API_BUTTON_CLICK_ERROR, | |
} from './actions/consts'; | |
import { getDataFromAPI } from './api'; | |
const getDataStarted = () => ({ type: API_BUTTON_CLICK }); | |
const getDataSuccess = data => ({ type: API_BUTTON_CLICK_SUCCESS, payload: data }) | |
const getDataError = message => ({ type: API_BUTTON_CLICK_ERROR. payload: message }); | |
const getDataFromAPI = () => { | |
return dispatch => { | |
dispatch(getDataStarted()); | |
getDataFromAPI() | |
.then(data => { | |
dispatch(getUserSuccess(data)); | |
}).fail(err => { | |
dispatch(getDataError(err.message)); | |
}) | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment