fids/browser-domain/src/hooks/useFetchFlights.tsx

36 lines
1.1 KiB
TypeScript

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<string | null>(null);
const [flights, setFlights] = useState<Flight[]>([]);
const [count, setCount] = useState<number>(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 };
};