import { Detail, ActionPanel, Action, showToast, Toast } from "@raycast/api";
import { useFetch } from "@raycast/utils";
const Demo = () => {
const { isLoading, data, mutate } = useFetch("https://api.example");
const appendFoo = async () => {
const toast = await showToast({ style: Toast.Style.Animated, title: "Appending Foo" });
try {
await mutate(
// we are calling an API to do something
fetch("https://api.example/append-foo"),
{
// but we are going to do it on our local data right away,
// without waiting for the call to return
optimisticUpdate(data) {
return data + "foo";
},
}
);
// yay, the API call worked!
toast.style = Toast.Style.Success;
toast.title = "Foo appended";
} catch (err) {
// oh, the API call didn't work :(
// the data will automatically be rolled back to its previous value
toast.style = Toast.Style.Failure;
toast.title = "Could not append Foo";
toast.message = err.message;
}
};
return (
<Detail
isLoading={isLoading}
markdown={data}
actions={
<ActionPanel>
<Action title="Append Foo" onAction={() => appendFoo()} />
</ActionPanel>
}
/>
);
};
类型
AsyncState
与函数的执行状态对应的对象。
// Initial State
{
isLoading: true, // or `false` if `options.execute` is `false`
data: undefined,
error: undefined
}
// Success State
{
isLoading: false,
data: T,
error: undefined
}
// Error State
{
isLoading: false,
data: undefined,
error: Error
}
// Reloading State
{
isLoading: true,
data: T | undefined,
error: Error | undefined
}