import { Method } from 'axios';
import { useEffect, useState } from 'react';
import { API } from '../controllers';
import { Status } from '../requests';

export const useAxios = (
  method: Method,
  url: string,
  payload?: any,
  headers?: any
) => {
  const [{ response, status, error }, setResponse] = useState<{
    status: Status['name'];
    response?: any;
    error?: any;
  }>({
    status: 'idle',
    response: null,
    error: null,
  });

  useEffect(() => {
    setResponse({ status: 'loading' });

    (async () => {
      try {
        const { data } = await API(method, url, payload, headers);

        setResponse({ status: 'success', response: data });
      } catch(err: any) {
        setResponse({ status: 'failed', error: err.response.data })
      }
    })();
  }, [method, url, payload, headers]);

  return [response, status, error];
};
