import { useEffect, useState } from 'react';
import { request } from 'utils/fetch';

export function useRequest<T = any>(param: string | { url: string; params?: {}; query?: {}; body?: string | FormData; options?: any }) {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<T>();
  const [error, setError] = useState();

  let url, params, query, body, options;
  if (typeof param === 'object') {
    ({ url, params, query, body, options } = param);
  } else {
    url = param;
  }

  async function refresh() {
    setLoading(true);
    try {
      const result = await request(url, params, query, body, options);
      setData(result);
    } catch (error) {
      setError(error);
    }
    setLoading(false);
  }

  useEffect(() => {
    (async () => {
      try {
        const result = await request(url, params, query, body, options);
        setData(result);
      } catch (error) {
        setError(error);
      }
      setLoading(false);
    })();
  }, []);

  return {
    loading,
    data,
    error,
    refresh
  };
}
