Using TakeLatest to Prevent Duplicate Calls
Showcase the use of TakeLatest effect to ensure that only the latest dispatched action of a specific type is handled, preventing duplicate API calls.
import { takeLatest, call, put } from 'redux-saga/effects';
Import the necessary effects from Redux-Saga.
function* fetchUserData(action) {
try {
const userData = yield call(Api.fetchUser, action.payload.userId);
yield put({type: 'FETCH_USER_SUCCESS', payload: userData});
} catch (e) {
yield put({type: 'FETCH_USER_FAILURE', message: e.message});
}
}
Define a worker saga to handle the API request.
function* mySaga() {
yield takeLatest('FETCH_USER_REQUEST', fetchUserData);
}
Define a watcher saga that uses takeLatest to initiate the worker saga on every latest dispatched 'FETCH_USER_REQUEST' action.