@ aspida/ swr
开始
安装
-
使用 无数字 :
$ npm install aspida @aspida/swr @aspida/axios swr axios # $ npm install aspida @aspida/swr @aspida/fetch swr # $ npm install aspida @aspida/swr @aspida/node-fetch swr node-fetch -
使用 雅伦数字 :
$ yarn add aspida @aspida/swr @aspida/axios swr axios # $ yarn add aspida @aspida/swr @aspida/fetch swr # $ yarn add aspida @aspida/swr @aspida/node-fetch swr node-fetch
从应用程序创建 HTTP 请求
src/index.ts
import aspida from "@aspida/axios"; // "@aspida/fetch", "@aspida/node-fetch"
import useAspidaSWR from "@aspida/swr";
import api from "../api/$api";
const client = api(aspida());
function Profile() {
const { data, error } = useAspidaSWR(client.user._userId(123), { query: { name: "mario" } });
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <div>hello {data.name}!</div>;
}
获得反应机构/状态/负责人
src/index.ts
import aspida from "@aspida/axios"; // "@aspida/fetch", "@aspida/node-fetch"
import useAspidaSWR from "@aspida/swr";
import api from "../api/$api";
const client = api(aspida());
function Profile() {
const { data, error } = useAspidaSWR(client.user._userId(123), "get", {
query: { name: "mario" },
});
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return (
<>
<div>Status: {data.status}</div>
<div>Headers: {JSON.stringify(data.headers)}</div>
<div>Name: {data.body.name}</div>
</>
);
}
useAspidaSWR(client.user._userId(123), { query }) 是一种异名 useAspidaSWR(client.user._userId(123), "$get", { query })
使用 SWR 选项
src/index.ts
import aspida from "@aspida/axios"; // "@aspida/fetch", "@aspida/node-fetch"
import useAspidaSWR from "@aspida/swr";
import api from "../api/$api";
const client = api(aspida());
function Profile() {
const { data, error } = useAspidaSWR(client.user._userId(123), {
query: { name: "mario" },
revalidateOnMount: true,
initialData: { name: "anonymous" },
});
if (error) return <div>failed to load</div>;
return <div>hello {data.name}!</div>;
}
有条件获取
如果你使用 enabled = false 选项,AspidaSWR将不会启动请求.
const { data: user } = useAspidaSWR(client.user);
const { data } = useAspidaSWR(client.articles, {
query: { userId: user?.id ?? 0 },
enabled: !!user,
});
// is an alias of
const { data } = useSWR(
user ? [client.articles.$path({ query: { userId: user.id } }), "$get"] : null,
() => client.articles.$get({ query: { userId: user.id } })
);
许可证
@aspida/swr根据 MIT 许可证。 。 。 .