@1771technologies/lytenyte-pro
Version:
Blazingly fast headless React data grid with 100s of features.
43 lines (42 loc) • 1.38 kB
JavaScript
import { useMemo, useRef, useState } from "react";
import { useEvent } from "@1771technologies/lytenyte-core/internal";
export function useAsyncOptions(p, clearOnQuery) {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const [options, setOptions] = useState([]);
const controllerRef = useRef(null);
const loadOptions = useEvent((query) => {
if (!p)
return;
if (controllerRef.current)
controllerRef.current.abort();
const opts = p(query);
if (Array.isArray(opts)) {
setOptions(opts);
return;
}
const controller = new AbortController();
controllerRef.current = controller;
if (clearOnQuery)
setOptions([]);
setLoading(true);
setError(null);
opts
.then((res) => {
if (controller.signal.aborted)
return;
setOptions(res);
})
.catch((e) => {
if (controller.signal.aborted)
return;
setError(e);
})
.finally(() => {
if (controller.signal.aborted)
return;
setLoading(false);
});
});
return useMemo(() => ({ loading, error, options, loadOptions }), [error, loadOptions, loading, options]);
}