useTransport.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { useEffect, useState, useCallback } from "react";
  2. import { apiForAuthenticated } from "@/api/api.config";
  3. import type { Transport } from "@/types/TransportType";
  4. interface UseTransportState {
  5. transport: Transport | null;
  6. loading: boolean;
  7. error: string | null;
  8. }
  9. export const useTransport = () => {
  10. const [state, setState] = useState<UseTransportState>({
  11. transport: null,
  12. loading: false,
  13. error: null,
  14. });
  15. const fetchTransport = useCallback(async () => {
  16. setState({ transport: null, loading: true, error: null });
  17. try {
  18. const response =
  19. await apiForAuthenticated.get<Transport>("/transport/my");
  20. setState({
  21. transport: response.data || null,
  22. loading: false,
  23. error: null,
  24. });
  25. } catch (error: any) {
  26. if (error.response?.status === 204 || error.response?.status === 404) {
  27. setState({ transport: null, loading: false, error: null });
  28. return;
  29. }
  30. console.error("Error fetching transport:", error);
  31. const errorMessage =
  32. error instanceof Error
  33. ? error.message
  34. : "Błąd podczas pobierania danych pojazdu";
  35. setState({ transport: null, loading: false, error: errorMessage });
  36. }
  37. }, []);
  38. useEffect(() => {
  39. let isMounted = true;
  40. fetchTransport()
  41. .then(() => {
  42. if (!isMounted) return;
  43. })
  44. .catch((error) => {
  45. console.error("Error in fetchTransport:", error);
  46. if (isMounted) {
  47. const errorMessage =
  48. error instanceof Error
  49. ? error.message
  50. : "Błąd podczas pobierania danych pojazdu";
  51. setState({ transport: null, loading: false, error: errorMessage });
  52. }
  53. });
  54. return () => {
  55. isMounted = false;
  56. };
  57. }, []);
  58. return { ...state, refetch: fetchTransport };
  59. };