To handle async operation challenges in React with redux-saga:
Install redux-saga:
npm install redux-saga
Create Saga Middleware:
import createSagaMiddleware from 'redux-saga';
const sagaMiddleware = createSagaMiddleware();
Configure Store:
import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import rootSaga from './sagas';
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
Write Saga for Async Call:
import { call, put, takeLatest } from 'redux-saga/effects';
function* fetchDataSaga() {
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 });
}
}
export default function* rootSaga() {
yield takeLatest('FETCH_REQUEST', fetchDataSaga);
}