Migrating from Redux Thunk to Redux Saga in Redux 5.0.0
Code snippet to showcase the process of migrating middleware for async operations from Redux Thunk to Redux Saga in the context of Redux 5.0.0.
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import rootSaga from './sagas';
// Create the Saga middleware
const sagaMiddleware = createSagaMiddleware();
// Mount it on the Store
const store = createStore(
rootReducer,
applyMiddleware(sagaMiddleware)
);
// Then run the saga
sagaMiddleware.run(rootSaga);
// Render the application
// render(<App store={store} />, document.getElementById('root'));
This code replaces Redux Thunk with Redux Saga as the middleware for handling asynchronous actions. It involves creating the Saga middleware, applying it to the store, and running the rootSaga which contains all of the Saga listeners.
import { takeEvery, put, call } from 'redux-saga/effects';
// Example of a worker saga
function* fetchUserData(action) {
try {
const data = yield call(Api.fetchUser, action.payload.userId);
yield put({ type: 'USER_FETCH_SUCCEEDED', payload: data });
} catch (error) {
yield put({ type: 'USER_FETCH_FAILED', payload: error.message });
}
}
// Example of a watcher saga
function* mySaga() {
yield takeEvery('USER_FETCH_REQUESTED', fetchUserData);
}
export default mySaga;
This example shows a worker saga to fetch user data and a watcher saga to trigger that worker come action with type 'USER_FETCH_REQUESTED'. The worker saga performs a call to an API and dispatches actions based on the API call's success or failure.