import React, { useCallback, useEffect } from "react"; import { useState } from "react"; import { User, Flight } from "../Types"; import { fetchFlights } from "../Api"; export const useFetchFlights = (origin: string | null, page: number | null) => { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [flights, setFlights] = useState([]); const [count, setCount] = useState(0); const fetchData = useCallback(async () => { setError(null); setIsLoading(true) fetchFlights(origin, page) .then((data) => { setCount(data.count) setFlights(data.flights); }) .catch((error) => { if (error.response.status == 404) { setCount(0) setFlights([]) } }) .finally(() => setIsLoading(false)) }, [origin, page]); useEffect(() => { fetchData() }, [fetchData]); return { flights, count, isLoading, error, fetchData }; };