To handle asynchronous actions in Redux using Redux-Saga for complex data-fetching scenarios, you follow these steps:
Install Redux-Saga:
npm install redux-saga
Create a Saga:
Define a worker saga for your asynchronous task. For instance, if you are fetching user data:
import { call, put } from 'redux-saga/effects';
import Api from './api'; // Your API logic
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({ type: 'FETCH_SUCCESS', payload: user });
} catch (error) {
yield put({ type: 'FETCH_FAILURE', payload: error.message });
}
}
Watch for Actions:
Create a watcher saga to listen for specific actions and invoke the worker saga:
import { takeEvery } from 'redux-saga/effects';
function* watchFetchUser() {
yield takeEvery('FETCH_REQUEST', fetchUser);
}
export default watchFetchUser;
Connect Saga Middleware:
Set up the saga middleware in your Redux store:
import createSagaMiddleware from 'redux-saga';
import { configureStore } from '@reduxjs/toolkit';
import rootSaga from './sagas'; // Combine multiple sagas if necessary
const sagaMiddleware = createSagaMiddleware();
const store = configureStore({
reducer: rootReducer, // Your root reducer
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(sagaMiddleware),
});
sagaMiddleware.run(rootSaga);
export default store;
Dispatch Actions:
Trigger actions from your UI, for example:
dispatch({ type: 'FETCH_REQUEST', payload: { userId: 1 } });