Migrating from redux-thunk to redux-saga
Example of refactoring an asynchronous action from redux-thunk to redux-saga due to the changes in Redux v5.0.0.
import { takeEvery, put, call } from 'redux-saga/effects';
import { FETCH_DATA, FETCH_DATA_SUCCESS, FETCH_DATA_FAILURE } from './actionTypes';
// Example of a fetch request using saga
function* fetchDataSaga(action) {
try {
const data = yield call(fetchDataFromApi, action.payload);
yield put({ type: FETCH_DATA_SUCCESS, payload: data });
} catch (error) {
yield put({ type: FETCH_DATA_FAILURE, payload: error.message });
}
}
// watcher saga listens for the FETCH_DATA action
function* watchFetchData() {
yield takeEvery(FETCH_DATA, fetchDataSaga);
}
export default watchFetchData;
// This assumes you have a fetchDataFromApi implemented which
// makes the API call and returns a promise.
This piece of code represents a Redux-saga saga that replaces a redux-thunk asynchronous action. It listens for a FETCH_DATA action, then calls fetchDataSaga, which attempts to load data using fetchDataFromApi function and dispatches a success or failure action.
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import watchFetchData from './sagas';
// creating the saga middleware
const sagaMiddleware = createSagaMiddleware();
// mount it on the Store
const store = createStore(
rootReducer,
applyMiddleware(sagaMiddleware)
);
// then run the saga
sagaMiddleware.run(watchFetchData);
export default store;
This JavaScript code sets up the Redux store, applies the redux-saga middleware, and starts the watcher saga that we defined in the previous step.