import { useEffect, useState } from "react";
export function useFetch(fetcher, opts) {
    if (Array.isArray(opts)) {
        opts = { deps: opts };
    }
    const options = (opts || {});
    const [error, setError] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
    const [data, setData] = useState(options.defaultValue);
    const fetch = () => {
        options.start && options.start();
        setIsLoading(true);
        return fetcher().then((result) => {
            setData(result);
            options.onSuccess && options.onSuccess(result);
        }).catch(error => {
            setError(error);
            options.onError && options.onError(error);
        }).finally(() => {
            setIsLoading(false);
            options.end && options.end();
        });
    };
    useEffect(() => {
        if (!options.condition || options.condition()) {
            fetch();
        }
    }, options.deps);
    return { data, isLoading, error, setData, refetch: fetch };
}
export function useFetchOnce(fetcher, opts) {
    if (!opts || Array.isArray(opts)) {
        opts = { deps: [] };
    }
    else if (opts) {
        opts.deps = [];
    }
    return useFetch(fetcher, opts);
}
//# sourceMappingURL=useFetch.js.map