Skip to content

Instantly share code, notes, and snippets.

@herbowicz
Created March 13, 2018 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save herbowicz/8f1eaacc201444f6e70bc817dcf7bc06 to your computer and use it in GitHub Desktop.
Save herbowicz/8f1eaacc201444f6e70bc817dcf7bc06 to your computer and use it in GitHub Desktop.
redux-thunk vs. redux-saga
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);
}
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