To integrate redux-saga middleware into a React project, follow these steps:
Step 1: Install Required Packages
In your React project directory, run:
npm install redux redux-saga react-redux
Step 2: Set Up Redux Store with Redux-Saga Middleware
Create your store.js:
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers'; // combine your reducers
import rootSaga from './sagas'; // your root saga
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
rootReducer,
applyMiddleware(sagaMiddleware)
);
sagaMiddleware.run(rootSaga);
export default store;
Step 3: Create a Saga File
Example: sagas.js
import { takeEvery, put, call } from 'redux-saga/effects';
function* fetchData(action) {
try {
const response = yield call(fetch, 'https://api.example.com/data');
const data = yield response.json();
yield put({ type: 'FETCH_SUCCESS', payload: data });
} catch (error) {
yield put({ type: 'FETCH_FAILURE', payload: error.message });
}
}
function* watchFetchData() {
yield takeEvery('FETCH_REQUEST', fetchData);
}
export default function* rootSaga() {
yield watchFetchData();
}
Step 4: Connect Redux Store to React
In your index.js or main.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Step 5: Dispatch Action in React Component
Example in a component:
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
function DataComponent() {
const dispatch = useDispatch();
const data = useSelector(state => state.data);
const loading = useSelector(state => state.loading);
const fetchData = () => {
dispatch({ type: 'FETCH_REQUEST' });
};
return (
<div>
<button onClick={fetchData}>Load Data</button>
{loading ? <p>Loading...</p> : <pre>{JSON.stringify(data)}</pre>}
</div>
);
}
export default DataComponent;