-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-create-todo-submit.ts
More file actions
63 lines (54 loc) · 2.01 KB
/
Copy pathuse-create-todo-submit.ts
File metadata and controls
63 lines (54 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"use client";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import type { TodoCreateRequest } from "@/api/generated/models";
import type { CreateTodoRequest } from "@/schemas/todo/todo-schema";
import { getGetHomeQueryKey } from "@/api/generated/endpoints/home/home";
import { useCreateTodo } from "@/api/generated/endpoints/todo/todo";
import { useStatisticsQueryInvalidation } from "@/hooks/statistics/use-statistics-query-invalidation";
import { todoCreateResponseSchema } from "@/schemas/todo/todo-schema";
const buildCreateTodoRequestBody = (
data: CreateTodoRequest,
): TodoCreateRequest => ({
icon: data.icon ?? undefined,
title: data.title,
subtasks: data.subtasks?.length ? data.subtasks : undefined,
date: data.date,
duration: data.duration,
priority: data.priority ?? undefined,
tagId: data.tagId ?? undefined,
repeatType: data.repeatType,
repeatWeekdays: data.repeatWeekdays?.length ? data.repeatWeekdays : undefined,
repeatDayOfMonth: data.repeatDayOfMonth ?? undefined,
memo: data.memo?.trim() ? data.memo : undefined,
});
export const useCreateTodoSubmit = () => {
const [isErrorToastOpen, setIsErrorToastOpen] = useState(false);
const { mutate: createTodo } = useCreateTodo();
const queryClient = useQueryClient();
const { invalidateStatistics } = useStatisticsQueryInvalidation();
const handleSubmit = (data: CreateTodoRequest) => {
createTodo(
{ data: buildCreateTodoRequestBody(data) },
{
onSuccess: (response) => {
const parsed = todoCreateResponseSchema.safeParse(response.data);
if (!parsed.success) {
setIsErrorToastOpen(true);
return;
}
queryClient.invalidateQueries({ queryKey: getGetHomeQueryKey() });
invalidateStatistics();
},
onError: () => {
setIsErrorToastOpen(true);
},
},
);
};
return {
handleSubmit,
isErrorToastOpen,
closeErrorToast: () => setIsErrorToastOpen(false),
};
};