从头开始创建一个自动产生文档/类型安全的现代API(18) 添加数据更新功能

添加更新数据的Hooks

为了能够方便调用 Hooks 修改数据,我对接口做了改造,body 参数加上了id,这样我们就可以在页面初始化时,不用指定 id,等调用时再根据 body 的 id 调用后台。
添加 hooks/use-update-task.ts:

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
import { InferRequestType,InferResponseType } from "hono";
import { useMutation, useQueryClient } from "@tanstack/react-query";

import { client } from "@/lib/hono"

type ResponseType = InferResponseType<typeof client.tasks[":id"]["$patch"]>;
type RequestType = InferRequestType<typeof client.tasks[":id"]["$patch"]>["json"];

interface UpdateTaskPayload {
id: number;
name?: string;
done?: boolean;
order?: number;
};

export const useUpdateTask = ( ) => {
const queryClient = useQueryClient();

const mutation = useMutation<
ResponseType,
Error,
RequestType
>({
mutationFn: async (json) => {
const response = await client.tasks[":id"]["$patch"]({
json,
param: { id: json.id },
});
return response.json();
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey:["tasks"]});
},
onError: () => {
console.log("task update failed");
},
});

return mutation;
}

修改page.tsx

修改 handleUpdateTask / handleToggleTask / handleDragEnd:

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
function handleToggleTask(task: Task) {
dispatch({
type: "changed",
task: { ...task, done: !task.done },
});

editMutation.mutate(
{
id: task.id,
done: !task.done
}
);
};

function handleUpdateTask(task: Task, newName: string) {
dispatch({
type: "changed",
task: { ...task, name: newName },
});

editMutation.mutate(
{
id: task.id,
name: newName
}
);

setEditingTask(null);
};

function handleDragEnd(event: DragEndEvent) {
const { active, over } = event

if (over && active.id !== over.id) {
const oldIndex = tasks.findIndex((task) => task.id === active.id)
const newIndex = tasks.findIndex((task) => task.id === over.id)

const newTasks = arrayMove(tasks, oldIndex, newIndex).map((task, index) => ({
...task,
order: index,
}));

dispatch({
type: "reordered",
tasks: newTasks,
});

newTasks.forEach((task) => {
editMutation.mutate(
{
id: task.id,
order: task.order
}
);
});
}
}

如果感兴趣本项目,请访问项目目录: 从头开始创建一个自动产生文档/类型安全的现代API 目录


作者:Bearalise
出处:从头开始创建一个自动产生文档/类型安全的现代API(18) 添加数据更新功能
版权:本文版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明,必须在文章中给出原文链接。

请我喝杯咖啡吧~

支付宝
微信