TIL. 중간다리! middle ware - 9/27

예흠·2020년 9월 27일
0

Redux

목록 보기
1/1

middle ware

출처:벨로퍼트

미들웨어는, 액션이 디스패치(dispatch) 되어서 리듀서에서 이를 처리하기전에 사전에 지정된 작업들을 설정합니다.
미들웨어를 액션과 리듀서 사이의 중간자라고 이해하시면 되겠습니다.

이러한 미들웨어는 비동기 처리를 할때 굉장히 유용하게 쓰입니다.

이제 예제들로 미들웨어를 한번 연습해 봅시다.

- 초기 세팅하기

먼저 create-react-app을 해서 빈 프로젝트를 하나 만들어 주고
버튼을 누르면 카운터가 증가 되거나 감소되는 기능을 가진 component를 만들어 줍니다.
그리고 리덕스 스토어를 만들어서 적용시켜주는 것 까지 해줍니다!

//redux store
const INCREASE = 'counter/INCREASE';
const DECREASE = 'counter/DECREASE';

export const increase = () => ({type: INCREASE});
export const decrease = () => ({type: DECREASE});

const initialState = 0;

export default function counter(state = initialState, action) {
  switch (action.type) {
    case INCREASE:
      return state + 1;
    case DECREASE:
      return state - 1;
    default:
      return state;
  }
}
//index.js (modules의 index)
import {combineReducers} from 'redux';
import counter from './counter';

const rootReducer = combineReducers({ counter });

export default rootReducer;
//CounterContainer.js (container폴더에 생성)
import React from 'react';
import Counter from '../component/Counter';
import { increase, decrease} from '../modules/counter';
import { useSelector, useDispatch} from 'react-redux';

const CounterContainer = () => {
  const number = useSelector(state => state.counter);
  const dispatch = useDispatch();

  const onIncrease = () => {dispatch(increase())};
  const onDecrease = () => {dispatch(decrease())};

  return (
    <Counter number={number} onIncrease={onIncrease} onDecrease={onDecrease} />
  );
};

export default CounterContainer;
//Counter.js (components 폴더에 생성)
import React from 'react';

const Counter = ({ number, onIncrease, onDecrease}) => {
  return (
    <div>
      <h1>{number}</h1>
      <button onClick={onIncrease}>+1</button>
      <button onClick={onDecrease}>-1</button>
    </div>
  );
};

export default Counter;

이렇게 초기세팅을 먼저 해줍니다.

- package 설치

이제 기본적인 패키지 들을 설치해 줍니다.
yarn add react-redux redux redux-logger redux-thunk
yarn add redux-devtools-extension

이렇게 해주고 index.js를 세팅해 줍니다.

- console창으로 확인해보자

미들웨어폴더를 만들어서 그 안에 myLogger.js를 만들어 줍니다.

이렇게 myLogger를 applyMiddleWare()이 안에 넣어주면 console창을 보면 아주 잘 나오게 됩니다.

하지만 더 좋은 redux-logger를 install 했기 때문에 써봅시다.

- redux-thunk

자 아까 install 했던 redux-thunk를 써보려고 합니다.

우리는 getPosts라는 action을 사용할 건데 이 함수는 function을 반환하는 함수기 때문에 thunk가 필요합니다.
그래서 redux-thunk를 import 시켜줍니다.
그러면 액션을 하면 어떻게 나올까요?

이렇게 이쁘게 나오는 군요!

여기까지는 아주 쉬운 입문 초기 세팅인것 같습니다.
다음 번에 더 깊이 들어가 봅시다.

profile
노래하는 개발자입니다.

0개의 댓글