To handle asynchronous actions in Redux for complex data fetching scenarios using Redux-Saga, follow these steps:
Steps to Handle Asynchronous Actions with Redux-Saga
Set Up Redux-Saga:
Install Redux-Saga: npm install redux-saga.
Create a root saga and integrate it with the Redux store.
Create Sagas for Data Fetching:
Use takeEvery, takeLatest, or other effects to listen for specific actions.
Perform asynchronous operations (e.g., API calls) using call and dispatch success/failure actions using put.
Handle Complex Scenarios:
Use fork, spawn, all, or race to manage multiple asynchronous tasks, parallel requests, or task cancellation.
Example Code
import { call, put, takeEvery, all } from 'redux-saga/effects';
import axios from 'axios';
// Action Types
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
// Action Creators
const fetchDataRequest = () => ({ type: FETCH_DATA_REQUEST });
const fetchDataSuccess = (data) => ({ type: FETCH_DATA_SUCCESS, payload: data });
const fetchDataFailure = (error) => ({ type: FETCH_DATA_FAILURE, payload: error });
// API Call
const fetchDataFromAPI = () => axios.get('https://api.example.com/data');
// Worker Saga
function* fetchDataSaga() {
try {
const response = yield call(fetchDataFromAPI);
yield put(fetchDataSuccess(response.data));
} catch (error) {
yield put(fetchDataFailure(error.message));
}
}
// Watcher Saga
function* watchFetchData() {
yield takeEvery(FETCH_DATA_REQUEST, fetchDataSaga);
}
// Root Saga
export default function* rootSaga() {
yield all([watchFetchData()]);
}
// Redux Store Setup
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './reducers';
import rootSaga from './sagas';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
sagaMiddleware.run(rootSaga);
export default store;