Middleware 미들웨어
- Custom functinoality로 Redux를 확장시키기 위한 방밥으로 권장되는 방식.
- Action을 dispatch할 때와 action이 reducer에 도달하는 순간의 사이에 third-party extension을 사용할 수 있도록 해준다.
- 로깅, 크래시 리포트, 비동기 처리등의 작업을 할 때 사용된다.
이 예제에서는 'redux-logger' 미들웨어를 사용해보았다.
이전 코드
// index.js
const redux = require('redux')
const createStore = redux.createStore
const combineReducers = redux.combineReducers
const BUY_CAKE = 'BUY_CAKE';
const BUY_ICECREAM = 'BUY_ICECREAM';
//action creator
function buyCake() {
return {
type: BUY_CAKE,
info: 'First redux action'
}
}
function buyIceCream() {
return {
type: BUY_ICECREAM,
}
}
const initialCakeState = {
numOfCakes: 10,
}
const initialIceCreamState = {
numOfIceCreams: 20
}
const cakeReducer = (state = initialCakeState, action) => {
switch(action.type){
case BUY_CAKE: return {
...state,
numOfCakes: state.numOfCakes - 1
}
default: return state
}
}
const iceCreamReducer = (state = initialIceCreamState, action) => {
switch(action.type){
case BUY_ICECREAM: return {
...state,
numOfIceCreams: state.numOfIceCreams - 1
}
default: return state
}
}
const rootReducer = combineReducers({
cake: cakeReducer,
iceCream: iceCreamReducer
})
const store = createStore(rootReducer);
console.log("initial state : ", store.getState());
const unsubscribe = store.subscribe(() => console.log("updated state :", store.getState()));
store.dispatch(buyCake()); //action of buying a cake
store.dispatch(buyCake());
store.dispatch(buyCake());
store.dispatch(buyIceCream());
store.dispatch(buyIceCream());
unsubscribe();
1. 터미널을 열어 아래 코드를 작성해 redux-logger를 install 한다.
npm i --save redux-logger
2. 'logger' 미들웨어를 import한다.
const redux = require('redux');
const reduxLogger = require('redux-logger'); //add this line
const createStore = redux.createStore;
const combineReducers = redux.combineReducers;
const logger = reduxLogger.createLogger(); //add this line
이 단계로 우리가 사용하려고 하는 'logger 미들웨어'를 app안에 포함하게 된다.
3. 아래 코드를 추가하여 미들웨어를 리덕스에 추가해준다.
'applyMiddleware' : middleware를 적용하기 위해 사용됨
const redux = require('redux');
const reduxLogger = require('redux-logger');
const createStore = redux.createStore;
const combineReducers = redux.combineReducers;
const applyMiddleWare = redux.applyMiddleware; //add this line
const logger = reduxLogger.createLogger();
4. 'createStore' 메소드이 두번째 인자를 추가해준다.
application에서 필요로하는 미들웨어를 무제한으로 넘겨줄 수 있다!
const rootReducer = combineReducers({
cake: cakeReducer,
iceCream: iceCreamReducer
})
//const store = createStore(rootReducer); //remove this line
const store = createStore(rootReducer, applyMiddleWare(logger)); //add this line
5. 작성해두었던 'console.log' 메소드를 지워준다.
이 역할을 추가한 미들웨어인 'logger'가 해주는 것이다.
//remove this line
//const unsubscribe = store.subscribe(() => console.log("updated state :", store.getState()));
const unsubscribe = store.subscribe(() => {}); //add this line
9. 터미널에 아래 코드를 작성하여 실행시켜준다.
node index //(파일명)
Results.
처음에 프린트 되어있는 'Initial state'는 logger가 아니라 작성해뒀던 코드에 의해 실행된 부분이다.
요약 - Redux middleware 사용법
1. 'applyMiddleware'를 import한다.
2. 'applyMiddleware()' 메소드에 middleware를 인자로 추가하여 'createStore()'의 두번째 인자로 넘긴다.
블로그에 영문 버전이 있으니 참고 바랍니다.
해당 포스팅은 유튜브 Codevolution의 'React Redux Tutorial'을 참고하여 작성되었습니다.
Github repository - https://github.com/rocher71/redux-demo
This commit - https://github.com/rocher71/redux-demo/commit/031859203afd69a86eca2b6fd5cd185e587896b9
'Frontend' 카테고리의 다른 글
[React Redux] Async actions, Redux Thunk Middleware (0) | 2023.09.22 |
---|---|
[React Redux] Redux Middleware, redux-logger (0) | 2023.09.22 |
[React Native] 노마드 코더 React Native 무료 강의 내용 정리 #3 Work hard travel hard app (0) | 2022.05.06 |
[React Native] 노마드 코더 React Native 무료 강의 내용 정리 #2 Weather App (0) | 2022.05.04 |
[React Native] 노마드 코더 React Native 무료 강의 내용 정리 #1 Introduction (0) | 2022.05.03 |