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

添加读取数据的Hooks

首先安装依赖:

1
bun add @tanstack/react-query

添加 hooks/use-get-tasks-list.ts:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { useQuery } from "@tanstack/react-query";
import { client } from "@/lib/hono"

export const useGetTasksList = () => {
const query = useQuery({
queryKey: ["tasks" ],
queryFn: async () => {
const res = await client.tasks.$get();

if(!res.ok){
throw new Error("Failed to fetch tasks list");
}

const data = await res.json();
return data;
},
});

return query;
};

添加支持模块 lib/hono.ts:

1
2
3
4
import { hc } from "hono/client";
import { AppType } from "@/app/api/[[...route]]/route";

export const client = hc<AppType>('/api');

注意:‘/api’ 是对应于 API 所在路径的。

修改page.tsx

添加 action

先添加定义:

1
2
type TaskAction =
| { type: "loaded"; tasks: Task[] }

再添加实现:

1
2
3
4
5
switch (action.type) {
case "loaded": {
// Sort tasks by order
return action.tasks.sort((a, b) => a.order - b.order)
}

实现页面加载时加载数据

加载数据:

1
2
3
4
const [dataLoaded, setDataLoaded] = React.useState(false)

const tasksQuery = useGetTasksList();
const isLoading = tasksQuery.isLoading;

使用useEffect处理数据加载,避免无限循环

1
2
3
4
5
6
7
React.useEffect(() => {
if (tasksQuery.data && tasksQuery.data.length > 0 && !dataLoaded) {
const tasksData = tasksQuery.data.map(({ createdAt, updatedAt, ...rest }) => rest);
dispatch({ type: "loaded", tasks: tasksData });
setDataLoaded(true);
}
}, [tasksQuery.data, dataLoaded]);

处理 Loading 状态

添加以下逻辑:

1
2
3
4
5
{isLoading ? (
<div className="flex justify-center p-8">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
) : (

测试效果

运行程序,可以看到数据成功加载:


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

请我喝杯咖啡吧~

支付宝
微信