Listening for Actions in Redux-Saga
Demonstrate how to listen for specific actions dispatched from a Redux store using 'takeEvery' and 'takeLatest' effects in Redux-Saga, to manage asynchronous tasks like fetching data from an API.
import { takeEvery, takeLatest, call, put } from 'redux-saga/effects';
import Api from './path/to/api';
Import necessary effects from redux-saga and the API module for making requests.
function* fetchUserData(action) {
try {
const data = yield call(Api.fetchUser, action.payload);
yield put({type: 'FETCH_USER_SUCCESS', data});
} catch (error) {
yield put({type: 'FETCH_USER_FAILURE', error});
}
}
Define a saga to fetch user data. It attempts to call the API and dispatches either a success or failure action.
function* watchFetchUserRequestEvery() {
yield takeEvery('FETCH_USER_REQUEST', fetchUserData);
}
Create a 'watcher' saga that listens for every 'FETCH_USER_REQUEST' action dispatched to the store and runs fetchUserData saga for each action.
function* watchFetchUserRequestLatest() {
yield takeLatest('FETCH_USER_REQUEST', fetchUserData);
}
Alternatively, create a 'watcher' saga that listens for a 'FETCH_USER_REQUEST' action and runs the fetchUserData saga only for the latest dispatched action, cancelling any previously started fetchUserData sagas if they are still running.