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:
40
web/src/hooks/use-data.tsx
Normal file
40
web/src/hooks/use-data.tsx
Normal 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,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user