Redux-Saga는 비동기 데이터처리, 에러 핸들링 과 테스트를 좀 더 쉽고 효율적으로 관리하기 위해 사용되는 Redux middleware이다.
https://redux-saga.js.org/logo/0800/Redux-Saga-Logo-Landscape.png
// saga.js
export function* helloSaga() {
console.log("Hello Sagas!");
} // 화살표 함수로는 generator 정의불가
// store.js
import { createStore, applyMiddleware } from "redux";
import createSagaMiddleware from "redux-saga";
import rootReducer from "./reducers/root";
import { helloSaga } from "./reducers/saga";
const sagaMiddleware = createSagaMiddleware();
const store = createStore(rootReducer, applyMiddleware(sagaMiddleware));
// Saga 사용 전에 반드시 applyMiddleware를 이용해서 연결해야한다.
sagaMiddleware.run(helloSaga);
export const action = (type) => store.dispatch({ type });
export default store;
import { all } from "redux-saga/effects";
const INCREMENT = "INCREMENT";
const INCREMENT_ASYNC = "INCREMENT_ASYNC";
function* helloSaga() {
console.log("Hello saga!");
}
export function* incrementAsync() {
...
}
export function* watchIncrementAsync() {
...
}
export default function* rootSaga() {
yield all([helloSaga(), watchIncrementAsync()]);
}
put
call
// 실제 실행을 saga안에서 한다.
function* fetchProducts(dispatch) {
const products = yield Api.fetch('/products')
dispatch({ type: 'PRODUCTS_RECEIVED', products })
}
import { call, put } from 'redux-saga/effects'
// saga는 명령만 하고 실제 실행은 middleware에서 한다.
function* fetchProducts() {
const products = yield call(Api.fetch, '/products')
yield put({ type: 'PRODUCTS_RECEIVED', products })
}
take
function* loginFlow() {
while (true) {
yield take('LOGIN')
// dispatch 된 LOGIN 액션을 잡아서 Login logic을 실행한다.
yield take('LOGOUT')
// ... perform the logout logic
}
}
takeEvery
takeLatest