Load data from api to the page

This commit is contained in:
2023-10-27 17:12:48 +07:00
parent 2723cc1694
commit d44eb6ff11
6 changed files with 153 additions and 72 deletions
+36
View File
@@ -0,0 +1,36 @@
import { useEffect, useState } from 'react';
// Constants
import { BASE_URL } from '../constants/path';
export const useFetch = (path: string) => {
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(false);
const [errorMsg, setErrorMsg] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
setIsPending(true);
try {
const response = await fetch(BASE_URL + path);
const json = await response.json();
if (!response.ok)
throw new Error(
`Error code: ${response.status} \n Messages: ${response.statusText}`,
);
setIsPending(false);
setData(json);
setErrorMsg(null);
} catch (error) {
setErrorMsg(`Could not fetch data.\n ${error}`);
setIsPending(false);
}
};
fetchData();
}, [path]);
return { data, isPending, errorMsg };
};