fix fetch hook
This commit is contained in:
@@ -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];
|
||||
|
||||
@@ -14,6 +14,6 @@ export const useI18n = () => {
|
||||
export const useI18nMd = (key) => {
|
||||
const i18n = useI18n();
|
||||
const fileName = i18n(key);
|
||||
const url = `${URL_RAW_PREFIX}/${fileName}`;
|
||||
return useFetch(fileName ? url : "");
|
||||
const url = fileName ?? `${URL_RAW_PREFIX}/${fileName}`;
|
||||
return useFetch(url);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user