%PDF- %PDF-
Mini Shell

Mini Shell

Direktori : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/
Upload File :
Create Path :
Current File : /home2/rezakur1/ai.rezakurnia.com/zh-router-frontend/src/hooks/useBilling.ts

import { useCallback, useEffect, useRef, useState } from "react";
import { apiRequest } from "@/lib/api";
import type { BillingResponse } from "@/types/api";

const REFRESH_INTERVAL_MS = 30_000;

interface UseBillingOptions {
  /** Ambil ulang otomatis tiap 30 detik (default true, dipakai halaman Billing). */
  autoRefresh?: boolean;
}

/**
 * Ringkasan billing user.
 * @param days 0 = semua waktu, >0 = N hari terakhir.
 */
export function useBilling(
  days = 0,
  { autoRefresh = true }: UseBillingOptions = {},
) {
  const [data, setData] = useState<BillingResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const reqId = useRef(0);

  const load = useCallback(async () => {
    const id = ++reqId.current;
    try {
      const res = await apiRequest<BillingResponse>(`/me/billing?days=${days}`);
      if (reqId.current !== id) return;
      setData(res);
      setError(null);
    } catch (e) {
      if (reqId.current !== id) return;
      setError(e instanceof Error ? e.message : "Gagal memuat billing");
    } finally {
      if (reqId.current === id) setLoading(false);
    }
  }, [days]);

  useEffect(() => {
    setLoading(true);
    load();
    if (!autoRefresh) return;
    const t = setInterval(load, REFRESH_INTERVAL_MS);
    return () => clearInterval(t);
  }, [load, autoRefresh]);

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

Zerion Mini Shell 1.0