Integrating Redux-Saga with Redux v5.0.0
Provide a practical example of how to integrate redux-saga with the updated middleware system in Redux v5.0.0.
import { configureStore } from '@reduxjs/toolkit';
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 = configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(sagaMiddleware)
});
// Then run the saga
sagaMiddleware.run(rootSaga);
export default store;
This snippet shows how to create a Redux store with sagas integrated using redux-saga and @reduxjs/toolkit. It creates the saga middleware, adds it to the store's middleware, and runs the saga.
import { takeEvery, put, call } from 'redux-saga/effects';
// Worker saga
function* fetchData(action) {
try {
const data = yield call(Api.fetchUser, action.payload.url);
yield put({type: 'FETCH_SUCCEEDED', data});
} catch (error) {
yield put({type: 'FETCH_FAILED', error});
}
}
// Watcher saga
function* watchFetchData() {
yield takeEvery('FETCH_REQUESTED', fetchData);
}
export default watchFetchData;
Defines the saga watchers and workers. The worker saga `fetchData` performs the API call and dispatches success or failure actions. The watcher saga `watchFetchData` listens for `FETCH_REQUESTED` actions to trigger the worker saga.
function rootReducer(state = {}, action) {
switch (action.type) {
case 'FETCH_SUCCEEDED':
return {...state, data: action.data, error: null};
case 'FETCH_FAILED':
return {...state, data: null, error: action.error};
default:
return state;
}
}
export default rootReducer;
Defines the root reducer with cases to handle the actions dispatched by sagas for successful or failed data fetches.
<!DOCTYPE html>
<html>
<head>
<title>Redux-Saga Example</title>
<script src="path_to_your_store.js"></script>
<!-- Include other scripts here -->
</head>
<body>
<div id="app"></div>
<!-- React Components will be mounted here -->
</body>
</html>
A basic HTML structure which includes the store configuration script. It provides a mounting point for a React application.
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
Ubuntu, Cantarell, 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#app {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
CSS styles providing basic global styles and centering the app's contents within the #app div.
const Api = {
fetchUser: (url) => { /* Implementation for fetching user */ }
};
export default Api;
A placeholder for the API object with a fetchUser function to simulate an asynchronous call to fetch user data.