FrontEnd
[React] 미들웨어 redux-saga 예제 (takeEvery, TaskLatest)
mingg123
2021. 8. 2. 17:22
redux-saga
기존 요청을 취소 처리해야 할 때 (불필요한 중복 요청 방지)
특정 액션이 발생했을 때 다른 액션을 발생시키거나, API요청 등 리덕스와 관계없는 코드를 실행할 때
웹소켓을 사용할 때
API 요청 실패 시 재요청을 해야할 때
yarn add redux-saga
counter.js
import { createAction, handleActions } from "redux-actions";
import { delay, put, takeEvery, takeLatest } from "redux-saga/effects";
const INCREASE = "counter/INCREASE";
const DECREASE = "counter/DECREASE";
export const increase = createAction(INCREASE);
export const decrease = createAction(DECREASE);
const INCREASE_ASYNC = "counter/INCREASE_ASYNC";
const DECREASE_ASYNC = "counter/DECREASE_ASYNC";
export const increaseAsync = createAction(INCREASE_ASYNC, () => undefined);
export const decreaseAsync = createAction(DECREASE_ASYNC, () => undefined);
function* increaseSaga() {
yield delay(1000);
yield put(increase());
}
function* decreaseSaga() {
yield delay(1000);
yield put(decrease());
}
export function* counterSaga() {
yield takeEvery(INCREASE_ASYNC, increaseSaga);
yield takeLatest(DECREASE_ASYNC, decreaseSaga);
}
const initialState = 0;
const counter = handleActions(
{
[INCREASE]: (state) => state + 1,
[DECREASE]: (state) => state - 1,
},
initialState
);
export default counter;
DECREASE 의 경우 takeLatest로 되어있기 때문에 여러 액션이 중첩되어 dispatch될 경우 기존것들은 무시하고 가장 마지막 액션만 처리한다.