useFetch
直接请求任意公网 HTTP(S) 接口的 React Hook,自带定时刷新、预览占位数据、过期请求自动取消与手动重载按钮支持。无需在 deskpack.json 填写任何域名白名单,写上 URL 就能用。
签名#
签名
const { data, loading, error, status, reload } = useFetch<MyData>(url, {
refreshMs: 5 * 60 * 1000,
fallback: sampleData,
});
参数#
urlstring | null必填- 要请求的公网
https://或http://地址。传null、undefined或空字符串时会暂停请求(适合等待用户填好参数后再发请求)。 options.refreshMsnumber可选- 自动定时刷新间隔(毫秒),只在桌面实时运行时生效,预览态自动暂停。
options.methodstring默认 "GET"- HTTP 请求方法,可选
"GET"、"POST"、"PUT"、"PATCH"、"DELETE"。 options.headersobject可选- 自定义请求头键值对,例如
{ Accept: "application/json", Authorization: "Bearer ..." }。 options.bodystring | object可选- 请求体:传字符串会原样发送;传对象或数组会自动转成 JSON 并附带
Content-Type: application/json。 options.responseTypestring默认 "json"- 响应解析方式:
"json"自动解析为对象,"text"返回原始文本字符串。 options.fallbackT可选- 首次请求完成前(以及预览态或刷新失败时)展示的兜底示例数据,防止卡片空白。
返回值#
dataT | null只读- 最新解析好的数据;若刷新失败会自动保留上一次成功的数据或
fallback。 loadingboolean只读- 当前是否有请求正在进行。
errorstring | null只读- 最近一次请求失败时的错误说明;正常时为
null。 statusnumber | null只读- HTTP 响应状态码(如
200、404、429)。 reloadfunction方法- 调用
reload()立即重新拉取一次,可直接绑定到刷新按钮的onClick。
示例:GitHub 仓库 Star 追踪(带定时刷新与手动重载)#
TSX
import React, { Button, HStack, Icon, Spacer, Text, VStack, useFetch, useWidget } from "deskset-react";
interface RepoInfo {
full_name: string;
stargazers_count: number;
open_issues_count: number;
}
const SAMPLE: RepoInfo = {
full_name: "swiftlang/swift",
stargazers_count: 68400,
open_issues_count: 7120,
};
export default function GitHubStars() {
const { settings, theme, t } = useWidget();
const repo = String(settings.repo || "swiftlang/swift").trim();
const { data, loading, error, reload } = useFetch<RepoInfo>(
repo ? `https://api.github.com/repos/${repo}` : null,
{
refreshMs: 15 * 60 * 1000,
headers: { Accept: "application/vnd.github+json" },
fallback: SAMPLE,
}
);
const info = data ?? SAMPLE;
return (
<VStack
maxWidth={true}
maxHeight={true}
padding={16}
spacing={8}
background={theme.isPure ? "clear" : "theme.card"}
cornerRadius={theme.isPure ? 0 : theme.corner}
clip={!theme.isPure}
>
<HStack alignment="center" spacing={6}>
<Icon name="star.fill" size={14} color="theme.warning" />
<Text fontSize={12} color="theme.secondary" lineLimit={1}>{info.full_name}</Text>
<Spacer />
<Button icon="arrow.clockwise" iconSize={12} variant="plain" onClick={reload} />
</HStack>
<Text fontSize={30} fontWeight="bold" monospacedDigits>
{info.stargazers_count.toLocaleString()}
</Text>
<Spacer />
<Text fontSize={11} color={error ? "theme.danger" : "theme.secondary"}>
{error
? t("网络请求失败,点右上角重试", "Refresh failed — tap to retry")
: loading
? t("更新中…", "Updating…")
: `Issues: ${info.open_issues_count.toLocaleString()}`}
</Text>
</VStack>
);
}
底层 fetch 与静默安全边界#
- 多步异步请求:在点击事件里需要连续发多次请求时,可用
const { fetch: widgetFetch } = useWidget();。 - 开箱即用 + 静默防内网攻击:公开 HTTP/HTTPS 地址可直接请求;宿主仅在底层静默拦截
localhost、127.0.0.1、局域网私有 IP、file://及重定向至内网的异常请求。 - 上限:单次响应体上限 2 MiB、超时 15 秒;预览态不发真实请求,直接展示
fallback。