To handle authentication token refresh in a React app using redux-saga:
Steps:
1. Intercept API calls to detect token expiry
Use a saga to catch 401 errors (unauthorized).
2. Trigger token refresh
Dispatch a REFRESH_TOKEN_REQUEST action to refresh tokens.
3. Queue failed requests (optional)
Hold failed requests, retry after refreshing.
Example Flow:
function* apiCallSaga(action) {
try {
const response = yield call(apiRequest, action.payload);
yield put({ type: 'API_SUCCESS', payload: response });
} catch (error) {
if (error.status === 401) {
yield put({ type: 'REFRESH_TOKEN_REQUEST', retryAction: action });
} else {
yield put({ type: 'API_FAILURE', payload: error });
}
}
}
function* refreshTokenSaga(action) {
try {
const newToken = yield call(refreshTokenAPI);
yield put({ type: 'REFRESH_TOKEN_SUCCESS', payload: newToken });
if (action.retryAction) {
yield put(action.retryAction);
}
} catch (error) {
yield put({ type: 'LOGOUT' }); // if refresh fails
}
}
function* watchAPI() {
yield takeEvery('API_REQUEST', apiCallSaga);
}
function* watchTokenRefresh() {
yield takeEvery('REFRESH_TOKEN_REQUEST', refreshTokenSaga);
}