"use client";

// src/hooks/use-self-fetch.ts
import { useEffect, useRef, useState } from "react";
function useSelfFetch(url, options) {
  const initialData = options?.initialData;
  const [data, setData] = useState(initialData ?? null);
  const [isLoading, setIsLoading] = useState(initialData === void 0 && url !== null);
  const [error, setError] = useState(false);
  const [reloadKey, setReloadKey] = useState(0);
  const dataUrlRef = useRef(initialData !== void 0 ? url : null);
  useEffect(() => {
    if (initialData !== void 0) setData(initialData);
  }, [initialData]);
  useEffect(() => {
    if (url === null) {
      setIsLoading(false);
      return;
    }
    if (dataUrlRef.current === url) return;
    const ctrl = new AbortController();
    let cancelled = false;
    async function load() {
      try {
        setIsLoading(true);
        setError(false);
        const res = await fetch(url, { signal: ctrl.signal });
        if (!res.ok) throw new Error(`Request failed (${res.status})`);
        const json = await res.json();
        if (!cancelled) {
          setData(json);
          dataUrlRef.current = url;
        }
      } catch (err) {
        if (cancelled || err?.name === "AbortError") return;
        setError(true);
        console.error("useSelfFetch:", url, err);
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
      ctrl.abort();
    };
  }, [url, reloadKey]);
  return {
    data,
    setData,
    isLoading,
    error,
    // Force a re-fetch of the current url: clear the held-url ref so the skip above
    // doesn't short-circuit, then bump the effect key.
    reload: () => {
      dataUrlRef.current = null;
      setReloadKey((k) => k + 1);
    }
  };
}

export {
  useSelfFetch
};
//# sourceMappingURL=chunk-L4LAAA5Q.js.map