|
| 1 | +import { unwrapResult } from "@reduxjs/toolkit" |
| 2 | +import { useCallback } from "react" |
| 3 | +import { useDispatch, useSelector } from "react-redux" |
| 4 | +import { Todo } from "../model" |
| 5 | +import { |
| 6 | + addTodoAction, |
| 7 | + deleteTodoAction, |
| 8 | + editTodoAction, |
| 9 | + fetchAllTodosAction, |
| 10 | + fetchTodoAction, |
| 11 | +} from "../store/todo/action" |
| 12 | +import { |
| 13 | + allTodoSelector, |
| 14 | + isFetchingSelector, |
| 15 | + todoSelector, |
| 16 | +} from "../store/todo/selector" |
| 17 | + |
| 18 | +/** |
| 19 | + * TODO custom hook |
| 20 | + */ |
| 21 | +export const useTodo = () => { |
| 22 | + const dispatch = useDispatch() |
| 23 | + const isFetching = useSelector(isFetchingSelector) |
| 24 | + const todo = useSelector(todoSelector) |
| 25 | + const todos = useSelector(allTodoSelector)?.map((t) => ({ |
| 26 | + id: t.id, |
| 27 | + name: t.name, |
| 28 | + complete: t.complete, |
| 29 | + createdAt: t.createdAt, |
| 30 | + updatedAt: t.updatedAt, |
| 31 | + })) |
| 32 | + |
| 33 | + const fetchAllTodos = useCallback( |
| 34 | + (arg?: { offset?: number; limit?: number }) => { |
| 35 | + return dispatch( |
| 36 | + fetchAllTodosAction({ |
| 37 | + offset: arg?.offset || 0, |
| 38 | + limit: arg?.limit || 5, |
| 39 | + }) |
| 40 | + ).then(unwrapResult) |
| 41 | + }, |
| 42 | + [dispatch] |
| 43 | + ) |
| 44 | + |
| 45 | + const fetchTodo = useCallback( |
| 46 | + (arg: { id: number }) => { |
| 47 | + return dispatch(fetchTodoAction(arg)).then(unwrapResult) |
| 48 | + }, |
| 49 | + [dispatch] |
| 50 | + ) |
| 51 | + |
| 52 | + const addTodo = useCallback( |
| 53 | + (arg: { todo: Todo }) => { |
| 54 | + return dispatch(addTodoAction(arg)).then(unwrapResult) |
| 55 | + }, |
| 56 | + [dispatch] |
| 57 | + ) |
| 58 | + |
| 59 | + const editTodo = useCallback( |
| 60 | + (arg: { todo: Todo }) => { |
| 61 | + return dispatch(editTodoAction(arg)).then(unwrapResult) |
| 62 | + }, |
| 63 | + [dispatch] |
| 64 | + ) |
| 65 | + |
| 66 | + const deleteTodo = useCallback( |
| 67 | + (arg: { id: number }) => { |
| 68 | + return dispatch(deleteTodoAction(arg)).then(unwrapResult) |
| 69 | + }, |
| 70 | + [dispatch] |
| 71 | + ) |
| 72 | + |
| 73 | + return { |
| 74 | + isFetching, |
| 75 | + todos, |
| 76 | + todo, |
| 77 | + fetchAllTodos, |
| 78 | + fetchTodo, |
| 79 | + addTodo, |
| 80 | + editTodo, |
| 81 | + deleteTodo, |
| 82 | + } as const |
| 83 | +} |
0 commit comments