import { useEffect, useState } from "react";
import { set } from "react-hook-form";
import { ApiRequestStatus } from "../const/api_request_states";

export const useGet = <T>(callback: () => Promise<T>) => {
  const [data, setData] = useState<T | null>(null);
  const [requestStatus, setRequestStatus] = useState(ApiRequestStatus.LOADING);

  const setLoading = async () => setRequestStatus(ApiRequestStatus.LOADING);

  const fetchData = async () => {
    try {
      await setLoading();
      const response = await callback();
      setData(response);
      setRequestStatus(ApiRequestStatus.SUCCESS);
    } catch (error) {
      setRequestStatus(ApiRequestStatus.ERROR);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const refresh = async () => {
    fetchData();
  };

  return { data, requestStatus, refresh };
};
