Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
1.3 kB
2
Indexable
Never
import axiosInstance from 'utils/axios';
import { useQuery } from '@tanstack/react-query';
import { DateRange } from '@mui/x-date-pickers-pro/models';
import { Dayjs } from 'dayjs';

interface DataPoint {
  x: string;
  y: number;
}

interface ProfitData {
  [key: string]: DataPoint[];
}

const fetchProfitData = async (accountId: number | null, period: string, dateRange: DateRange<Dayjs>): Promise<ProfitData> => {
  const params: any = { period };

  if (period === 'custom' && dateRange) {
    params.date_range = 'custom';
    params.start_date = dateRange[0] ? dateRange[0].format('YYYY-MM-DD') : '';
    params.end_date = dateRange[1] ? dateRange[1].format('YYYY-MM-DD') : '';
  } else if (period === 'All') {
    params.date_range = 'All';
  }

  const response = await axiosInstance.get(`/dashboard/profit-data/${accountId}`, { params });
  return response.data.data;
};

const useProfitData = (accountId: number | null, period: string, dateRange: DateRange<Dayjs>) => {
  return useQuery<ProfitData>({
    queryKey: ['profitData', accountId, period, dateRange],
    queryFn: () => fetchProfitData(accountId, period, dateRange),
    enabled: !!accountId && !!dateRange, //If there is no accountId or dateRange, we won't try to fetch
    staleTime: 1000 * 60 * 5 // Cache data for 5 minutes
  });
};

export default useProfitData;
Leave a Comment