Listening for Actions with takeEvery
Illustrate the use of `takeEvery` effect to listen for dispatched actions and trigger associated sagas for handling asynchronous operations.
import { takeEvery, call, put } from 'redux-saga/effects';
First, we import the necessary effects from redux-saga.
import { FETCH_DATA_REQUEST, fetchDataSuccess, fetchDataFailure } from './actions';
Import our action types and action creators for success and failure responses.
function* fetchDataSaga(action) {
try {
const data = yield call(apiFetch, action.payload); // Call API
yield put(fetchDataSuccess(data)); // Dispatch success action with data
} catch (error) {
yield put(fetchDataFailure(error)); // Dispatch failure action
}
}
Define a saga that calls an API and dispatches success or failure actions based on the response.
function* watchFetchData() {
yield takeEvery(FETCH_DATA_REQUEST, fetchDataSaga);
}
This saga listens for the FETCH_DATA_REQUEST action and triggers fetchDataSaga each time the action is dispatched.
export default watchFetchData;
Export the saga that watches for data fetch requests.