import { useEffect, useState } from 'react';

import { customRequest } from 'helpers/http';

export const useFetchData = (
  url: string,
  type: 'post' | 'get',
  defaultQuery?: any,
  disableReq?: any,
  errorCallBack?: () => void,
) => {
  const [data, setData] = useState<any>();
  const [reqQuery, setReqQuery] = useState<any>(defaultQuery);
  const [loading, setLoading] = useState<boolean>(false);
  const fetchData = async (query?: any) => {
    if (!url) return;
    setLoading(true);
    try {
      const res = await customRequest(url, type, query);
      setData(res);
      setReqQuery(query);
    } catch (error) {
      console.error(error);
      errorCallBack && errorCallBack();
    }
    setLoading(false);
  };

  useEffect(() => {
    !disableReq && url && fetchData(defaultQuery);
  }, []);
  return { data, loading, fetchData, reqQuery };
};
