typesafe-actions

typesafe-actions 라이브러리

action을 일일이 만들어주어야 하는 원래 방식과는 달리
createStandardAction을 사용하면 action을 쉽게 만들어서 사용할수있다.

적용전 code

const INCREASE = 'counter/INCREASE' as const;
const DECREASE = 'counter/DECREASE' as const;
const INCREASE_BY = 'counter/INCREASE_BY' as const;

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

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

export const increaseBy = (diff: number) => ({
    type: INCREASE_BY,
    payload: diff
})

type CounterAction = 
    | ReturnType<typeof increase>
    | ReturnType<typeof decrease>
    | ReturnType<typeof increaseBy>;
    
type CounterState = {
    count: number;
}

const initialState: CounterState = {
    count: 0
};

function counter(
    state: CounterState = initialState,
    action: CounterAction
) : CounterState {
    switch(action.type){
        case INCREASE:
            return {count: state.count + 1};
        case DECREASE:
            return {count: state.count - 1};
        case INCREASE_BY:
            return {count: state.count + action.payload};
        default:
            return state;
    }
}

export default counter;

적용후 코드

// **  typesafe-actions 라이브러리 사용
import {deprecated, ActionType, createReducer} from 'typesafe-actions';

const {createStandardAction} = deprecated

// // 액션 type 선언
const INCREASE = 'counter/INCREASE';
const DECREASE = 'counter/DECREASE';
const INCREASE_BY = 'counter/INCREASE_BY';

// 액션 생성함수를 선언합니다
export const increase = createStandardAction(INCREASE)();
export const decrease = createStandardAction(DECREASE)();
export const increaseBy = createStandardAction(INCREASE_BY)<number>(); // payload 타입을 Generics 로 설정해주세요.

const actions = { increase, decrease, increaseBy};
type CounterAction = ActionType<typeof actions>;

type CounterState = {
    count: number;
};

const initialState: CounterState = {
    count : 0
};

// 객체 형식으로 입력
const counter = createReducer<CounterState, CounterAction>(initialState, {
    [INCREASE] : state => ({ count: state.count + 1}),
    [DECREASE]: state => ({ count: state.count - 1}),
    [INCREASE_BY]: (state, action) => ({ count: state.count + action.payload })
});
    
export default counter;

** 참고 : https://react.vlpt.us/using-typescript/05-ts-redux.html

좋은 웹페이지 즐겨찾기