Helper to create typed actions or action creators in React+Redux+TypeScript apps.
With npm:
$ npm install --save create-action-ts
With yarn:
$ yarn add create-action-ts
createAction(type[, payload, meta]);
Parameters:
type
— Required. String as a type of the action.payload
— Any type of payload.meta
— Any type of meta information.
const action = createAction('counter', 5);
// -> { type: "counter", payload: 5 }
const actionCreator = (count: string) => createAction('counter', count);
// -> (count: string): { type: "counter", payload: string }
Let's say, you have a structure of the container below:
├─ components
└─ containers
└─ SomePage
├─ actions.ts
├─ constants.ts
├─ index.tsx
├─ reducer.ts
└─ types.ts
- Describe possible action keys by
enum
from TypeScript:
/* constants.ts */
export enum ActionKeys {
SET_USER_INFO = 'SET_USER_INFO',
RESET_USER_INFO = 'RESET_USER_INFO',
TOGGLE_ACCORDION = 'TOGGLE_ACCORDION',
}
- Create Action creators by
createAction()
function:
/* actions.ts */
import createAction from 'create-action-ts';
import { ActionKeys } from 'constants.ts';
export const setUserInfo = (id: string) => createAction(ActionKeys.SET_USER_INFO, id);
export const resetUserInfo = () => createAction(ActionKeys.RESET_USER_INFO);
export const toggleAccordion = (meta: { name: string }) => createAction(ActionKeys.TOGGLE_ACCORDION, null, meta);
- Describe all types of the Action creators and the Actions we need:
/* types.ts */
import { resetUserInfo, setUserInfo, toggleAccordion } from 'actions.ts';
export type SetUserInfoActionCreator = typeof setUserInfo;
export type ResetUserInfoActionCreator = typeof resetUserInfo;
export type ToggleAccordionActionCreator = typeof toggleAccordion;
export type ActionType =
ReturnType<SetUserInfoActionCreator> |
ReturnType<ResetUserInfoActionCreator> |
ReturnType<ToggleAccordionActionCreator>;
- Use the types in reducer:
/* reducer.ts */
import { ActionKeys } from 'constants.ts';
import { ActionType, StoreType } from 'types.ts';
export default function reducer(state: StoreType, action: ActionType) {
switch (action.type) { /* ... */ }
}
container's template:
/* index.tsx */
import React, { PureComponent } from 'react';
import { SetUserInfoActionCreator, ResetUserInfoActionCreator, ToggleAccordionActionCreator } from 'types.ts';
interface PropsType {
resetUserInfo: ResetUserInfoActionCreator,
setUserInfo: SetUserInfoActionCreator,
toggleAccordion: ToggleAccordionActionCreator,
}
class Page extends PureComponent<PropsType> {
render() { /* ... */ }
}
or anywhere else...
$ git clone [email protected]:ahtohbi4/create-action-ts.git
$ cd create-action-ts
$ npm install
$ npm run test