Skip to content

Instantly share code, notes, and snippets.

@JaysonChiang
Last active February 28, 2021 16:26
Show Gist options
  • Save JaysonChiang/c6e81d7cb6d8b02643c78c43ac3288d2 to your computer and use it in GitHub Desktop.
Save JaysonChiang/c6e81d7cb6d8b02643c78c43ac3288d2 to your computer and use it in GitHub Desktop.
Adding an Action Type Enum
enum ActionType {
ADD_TODO = 'add_todo',
ADD_TODO_SUCCESS = 'add_todo_success',
ADD_TODO_ERROR = 'add_todo_error',
}
interface TodoState {
loading: boolean;
error: string | null;
data: string[];
}
interface AddTodoAction {
type: ActionType.ADD_TODO;
}
interface AddTodoSuccessAction {
type: ActionType.ADD_TODO_SUCCESS;
payload: string[];
}
interface AddTodoErrorAction {
type: ActionType.ADD_TODO_ERROR;
payload: string;
}
type Action = AddTodoAction | AddTodoSuccessAction | AddTodoErrorAction;
const initialState = {
loading: false,
error: null,
data: [],
}
const reducer = (
state: TodoState = initialState,
action: Action
): TodoState => {
switch (action.type) {
case ActionType.ADD_TODO:
return { loading: true, error: null, data: [] };
case ActionType.ADD_TODO_SUCCESS:
return { loading: false, error: null, data: action.payload };
case ActionType.ADD_TODO_ERROR:
return { loading: false, error: action.payload, data: [] };
default:
return state;
}
};
export default reducer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment