TIL | #22 React | function* Generator, redux-saga

trevor1107·2021년 4월 15일
0

2021-04-13(화)

function* Generator

제너레이터 함수는 function*으로 선언하고, 이 함수는 Generator 객체를 반환 한다. yield 키워드로 반환 시킬 수 있다.

yield 키워드는 next()를 사용하면 다음 yield로 넘어간다. 예제로 살펴보자.

function* idMaker(){
  var index = 0;
  while(index < 3)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined

// -------------------------------------------- //

function* anotherGenerator(i) {
  yield i + 1;
  yield i + 2;
  yield i + 3;
}

function* generator(i){
  yield i;
  yield* anotherGenerator(i);
  yield i + 10;
}

var gen = generator(10);

console.log(gen.next().value); // 10 (yield i가 리턴된다)
console.log(gen.next().value); // 11 (anotherGenerator(i)호출 리턴)
console.log(gen.next().value); // 12 (anotherGenerator(i)호출 리턴)
console.log(gen.next().value); // 13 (anotherGenerator(i)호출 리턴)
console.log(gen.next().value); // 20 (yield i + 10이 리턴)

redux-saga

리액트/리덕스 애플리케이션의 사이드 이펙트, 예를 들면 데이터 fetching이나 브라우저 캐시에 접근하는 순수하지 않은 비동기 동작들을, 더 쉽고 좋게 만드는 것을 목적으로하는 라이브러리이다.

리덕스 미들웨어이다. 따라서 앞서 말한 쓰레드가 메인 애플리케이션에서 일반적인 리덕스 액션을 통해 실행되고, 멈추고, 취소될 수 있게 한다. 또한 모든 리덕스 애플리케이션의 상태에 접근할 수 있고 리덕스 액션 또한 dispatch 할 수 있다.

yarn add redux-saga

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); // 1초 기다림
    yield put(increase()); // 특정 액션 디스패치
}

function* decreaseSaga() {
    yield delay(1000); // 1초 기다림
    yield put(decrease()); // 특정 액션 디스패치
}

export function* counterSaga() {
    // takeEvery : 들어오는 모든 액션에 대해 특정 작업을 처리한다.
    yield takeEvery(INCREASE_ASYNC, increaseSaga);
    // takeLatest : 기존에 진행중이던 작업이 있으면 취소시키고
    // 가장 마지막으로 실행된 작업만 수행한다.
    yield takeLatest(DECREASE_ASYNC, decreaseSaga);
}
// App.js
// ...
import createSagaMiddleware from 'redux-saga';
const sagaMiddleware = createSagaMiddleware();

// 미들웨어 등록
const store = createStore(
    rootReducer,
    composeWithDevTools(applyMiddleware(logger, ReduxThunk, sagaMiddleware))
);

// 사가 미들웨어 실행
sagaMiddleware.run(rootSaga);
profile
프론트엔드 개발자

0개의 댓글