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

View File

@@ -14,6 +14,6 @@ export const useI18n = () => {
export const useI18nMd = (key) => { export const useI18nMd = (key) => {
const i18n = useI18n(); const i18n = useI18n();
const fileName = i18n(key); const fileName = i18n(key);
const url = `${URL_RAW_PREFIX}/${fileName}`; const url = fileName ?? `${URL_RAW_PREFIX}/${fileName}`;
return useFetch(fileName ? url : ""); return useFetch(url);
}; };