mirror of
https://github.com/Nezumi-2711/react-training.git
synced 2026-09-22 13:38:51 +00:00
Load data from api to the page
This commit is contained in:
@@ -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 };
|
||||
};
|
||||
Reference in New Issue
Block a user