fix fetch hook

This commit is contained in:
Gabe Yuan
2023-08-14 14:58:57 +08:00
parent d4be34d689
commit bcb9974253
2 changed files with 22 additions and 14 deletions

View File

@@ -13,19 +13,27 @@ export const useFetch = (url) => {
if (!url) {
return;
}
setLoading(true);
fetch(url)
.then((res) => {
if (res.ok) {
if (res.headers.get("Content-Type")?.includes("json")) {
return res.json().then(setData);
}
return res.text().then(setData);
(async () => {
setLoading(true);
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error(`[${res.status}] ${res.statusText}`);
}
setError(`[${res.status}] ${res.statusText}`);
})
.catch(setError)
.finally(() => setLoading(false));
let data;
if (res.headers.get("Content-Type")?.includes("json")) {
data = await res.json();
} else {
data = await res.text();
}
setData(data);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
})();
}, [url]);
return [data, loading, error];