m/cup
1
0
mirror of https://github.com/sergi0g/cup.git synced 2025-11-16 09:03:46 -05:00

refactor: better data fetching (#100)

This commit is contained in:
Raphaël Catarino
2025-05-02 18:12:19 +02:00
committed by GitHub
parent 2ac036d353
commit 5ea924c5ad
4 changed files with 76 additions and 14 deletions

View File

@@ -0,0 +1,40 @@
import { useEffect, useState } from "react";
import type { Data } from "../types";
export const useData = () => {
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [data, setData] = useState<Data | null>(null);
useEffect(() => {
if (isLoading || isError || !!data) return;
setIsLoading(true);
setIsError(false);
setData(null);
fetch(
process.env.NODE_ENV === "production"
? "./api/v3/json"
: `http://${window.location.hostname}:8000/api/v3/json`,
)
.then((response) => {
if (response.ok) return response.json();
throw new Error("Failed to fetch data");
})
.then((data) => {
setData(data as Data);
})
.catch((error: unknown) => {
setIsError(true);
console.error(error);
})
.finally(() => {
setIsLoading(false);
});
}, [data, isError, isLoading]);
return {
data,
isLoading,
isError,
};
};