Actions
프로젝트별로 필요사항이 다 다르고, 팀별로 컨벤션도 다 달라서 어느정도의 일관성과 통일성을 유지하기 위해 나온 라이브러리라고 보면 된다.
typesafe-actions
라이브러리에서는 몇가지 액션생성 함수를 제공한다.v4 버전 함수 쓰기
v5버전에서 내용이 많이 수정되었다. v4 버전의 함수들을 사용하고 싶다면 deprecated 에서 받아서 쓰면 된다.
import { deprecated } from "typesafe-actions" const { createAction, createStandardAction, createCustomAction } = deprecated;
1. createAction
- @V5
v4버전의
createStandardAction
이 v5버전에서 createAction
이 되었고 .map
메소드를 기입 않도록 간략화됐다. ( Flux Standard Action 생성 )FSA 액션은 ({type
,payload
,meta
,error
}) 형태로 고정이다.
생성 편의를 위해 필요없는 프로퍼티는 생략해도 되지만, 추가로 늘릴 순 없다.
import { createAction } from "typesafe-actions" const withPayloadAndMeta = createAction( 'CREATE_ACTION', (id: number, token: string) => id, // payload creator (id: number, token: string) => token // meta creator })(); // payload, meta, error가 필요없다면 이렇게 단순화할 수 있음. export const myListInit = createAction('MYLIST_INIT')();
2. createCustomAction
- @V5
프로퍼티를 커스텀해서 쓰고싶을 때 사용하면 됨.
v5버전으로 오면서 API가 더 단순해졌다.
import { createCustomAction } from 'typesafe-actions'; // before (v4) const add = createCustomAction('CUSTOM', type => { return (first: number, second: number) => ({ type, customProp1: first, customProp2: second }); }); // after (v5) const add = createCustomAction( 'CUSTOM', (first: number, second: number) => ({ customProp1: first, customProp2: second }) );
const add = createCustomAction('todos/ADD', (title: string) => ({ type, id: cuid(), title, completed: false }); ); // add: (title: string) => { type: "todos/ADD"; id: string; title: string; completed: boolean; }
3. RootAction 만들기
추천 앱에서 사용 가능한 모든 액션타입을 나타내는RootAction
을 만들어 써라. 써드파티의 액션타입들과 결합해서 명시해도 된다.
// types.d.ts // example of including `react-router` actions in `RootAction` import { RouterAction, LocationChangeAction } from 'react-router-redux'; import { TodosAction } from '../features/todos'; type ReactRouterAction = RouterAction | LocationChangeAction; export type RootAction = | ReactRouterAction | TodosAction;