import { useState, useEffect } from "react";
import axios from 'axios';
// define the base url
export const api = axios.create({
baseURL: 'http://localhost:3333',
});
const useFetch<T = unkown> =(url:string, options: AxiosrequestConfig)=>{
const [data, setData] = useState<T | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<Error | null)(null);
useEffect(()=>{
api.get(url, options)
.then(response => {setData(response.data)})
.catch(err => setError(err))
.finally(()=> setIsLoading(false))
}, [])
return {data, isLoading, error}
}
//implementing the hook
const App = () =>{
const {data, isLoading, error} = useFetch<DataType[]>('url');
return(
// set loading
{isLoading && <p>Loading...</p>}
// set data map
{data?.map(item=> item)}
)
}