Open this example in the interactive library
Live preview
Source code
// components/ClickToFetchResult.tsx
import { useState } from "react";
const defaultLoad = async () => "Up to date";
export default function ClickToFetchResult({
load = defaultLoad,
}: { load?: () => Promise<string> } = {}) {
const [result, set] = useState("");
const [busy, wait] = useState(false);
return (
<div>
<button
disabled={busy}
onClick={async () => {
wait(true);
try {
set(await load());
} catch {
set("Request failed");
} finally {
wait(false);
}
}}
>
Fetch result
</button>
<output>{busy ? "Loading…" : result}</output>
</div>
);
}
