import { useState } from 'react';

export function useApi<ApiResponse = unknown>(
  apiFunction: () => Promise<ApiResponse>
) {
  const [data, setData] = useState<ApiResponse>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const onApi = () => {
    setIsLoading(true);
    return apiFunction()
      .then((response) => {
        setData(response);
        return response;
      })
      .catch((error) => {
        setError(error);
        return Promise.reject(error);
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  return { data, error, isLoading, onApi };
}
