useFetch
HOOK

HOOKS & API / NETWORK

useFetch

Fetch public HTTP(S) JSON or text APIs directly from your widget, with built-in periodic polling, preview fallback data, automatic cancellation, and manual reload. No domain allowlist in deskpack.json is needed.

Signature#

SIGNATURE
const { data, loading, error, status, reload } = useFetch<MyData>(url, {
  refreshMs: 5 * 60 * 1000,
  fallback: sampleData,
});

Parameters#

urlstring | nullRequired
Public https:// or http:// URL. Pass null, undefined, or "" to skip fetching until a condition is met.
options.refreshMsnumberOptional
Automatic polling interval in milliseconds while live on the desktop (paused in preview mode).
options.methodstringDefault "GET"
HTTP verb: "GET", "POST", "PUT", "PATCH", or "DELETE".
options.headersobjectOptional
Custom request headers map (e.g. { Accept: "application/json" }).
options.bodystring | objectOptional
Request payload: strings are sent verbatim; objects or arrays are JSON-serialized with Content-Type: application/json.
options.responseTypestringDefault "json"
"json" parses JSON automatically; "text" returns the raw response string.
options.fallbackTOptional
Sample payload shown before the first fetch completes (and preserved during preview mode or failed refreshes).

Return Value#

dataT | nullRead-only
Latest parsed payload; keeps the previous success value or fallback if a refresh fails.
loadingbooleanRead-only
true while a request is currently in flight.
errorstring | nullRead-only
Error message from the latest failure, or null when healthy.
statusnumber | nullRead-only
HTTP status code (e.g. 200, 404, 429).
reloadfunctionMethod
Call reload() to trigger an immediate refetch (great for a refresh button's onClick).

Example: Live GitHub Stars Card with Polling & Manual Refresh#

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>
  );
}

Imperative fetch & Invisible Sandbox Safety#

  • Chained async requests: Inside click handlers, use const { fetch: widgetFetch } = useWidget() to preserve widget identity across sequential await calls.
  • Zero-config public access + automatic SSRF guard: Public HTTP(S) endpoints work immediately; Deskset silently blocks localhost, 127.0.0.1, private LAN IPs, file://, URL credentials, and redirects to private hosts.
  • Limits: Response bodies are capped at 2 MiB with a 15-second timeout; requests never fire in preview mode.