NGRX에서 제공하는 Meta-reducer에 대해 알아보자

NGRX에서 제공하는 Meta-reducer에 대해 알아보자

Meta-reducer는 reducer를 받고 새로운 reducer를 return하는 higher order reducer입니다.

NgRx 공식 문서에 따르면, Meta-reducer는 action -> reducer 파이프 라인 사이의 hook으로 동작합니다.

그래서 실행 흐름은 action -> meta reducer -> reducer 이러한 순서로 진행됩니다.

Meta-reducer는 아래와 같은 상황에서 매우 유용합니다.

로그인 local / browser 저장소에서 app state를 받아야 할 때 로그아웃하여 app state를 clear / reset 시켜야 할 때

예를 들어, Angular 웹 애플리케이션에서 로그아웃시 전체 app state를 초기 상태로 재설정해야 하는 매우 자주 발생하는 상황을 예시로 들어보겠습니다.

‘clearState’라는 Meta-reducer를 만듭니다. (ActionReducer는 Action과 State를 받아 State를 리턴합니다)

export function clearState(reducer: ActionReducer):Actionreducer { return function (state, action) { // reducer를 return if (action.type === ActionTypes.LOGOUT) { state = undefined; } return reducer(state, action); // state를 return }; }

이제 app.module.ts 안에 metaReducer 배열을 선언하여 그 안에 clearState를 정의합니다.

export const metaReducers: MetaReducer[] = [clearState];

그리고 app.module.ts 안에 있는 @NgModule imports 안에 아래와 같이 넣어주면 로그아웃시 모든 state 가 초기화 상태로 세팅될 것입니다.

StoreModule.forRoot(appReducers, { metaReducers })

로그아웃 시 흐름을 표현하면 아래와 같습니다.

로그아웃 Action을 dispatch -> clearState Meta-reducer가 state를 undefined로 세팅하고 새로운 reducer를 return -> 모든 reducer들이 초기 상태를 return 하기 때문에 app state가 리셋됨.

로그인시 이메일이나 아이디를 기억하기 위해 localStorage에 저장해야 하는 경우에도 이 Meta-reducer와 ngrx-store-localstorage 라이브러리를 같이 활용하여 사용할 수 있습니다.

from http://clap-yeon.tistory.com/50 by ccl(A) rewrite - 2021-11-25 10:26:46