UNPKG

mantine-entity

Version:

A library combining Mantine, TanStack Query, and Mantine React Table for efficient entity management

53 lines (52 loc) 2.12 kB
/* eslint-disable @typescript-eslint/no-explicit-any */ "use client"; import { jsx as _jsx } from "react/jsx-runtime"; import { Loader, MultiSelect } from "@mantine/core"; import { forwardRef, useEffect, useMemo, useState } from "react"; import { processData } from "../utils"; const AsyncMultiSelect = forwardRef((props, ref) => { const [loading, setLoading] = useState(false); const [data, setData] = useState(props.data ?? []); const { dataSource, ...other } = props; const url = dataSource?.url ?? ""; const memoData = useMemo(() => data, [data]); const memoValue = useMemo(() => props.value, [props.value]); const fetchData = async () => { if (!url || loading || memoData.length > 0 || !dataSource?.httpGet || !dataSource?.getBaseUrl) return; setLoading(true); try { const response = await dataSource?.httpGet(dataSource.getBaseUrl(url)); const result = response; let processedData = []; if (dataSource?.mapData) { processedData = dataSource.mapData(result) ?? []; } else if (Array.isArray(result)) { processedData = processData({ data: result, valueKey: dataSource?.valueKey, labelKey: dataSource?.labelKey, placeholder: [], }); } setData(processedData); } catch (error) { console.error("Failed to fetch data:", error); } finally { setLoading(false); } }; useEffect(() => { if (memoValue && memoValue?.length > 0) { fetchData(); } }, [memoValue]); return (_jsx(MultiSelect, { ...other, data: memoData, ref: ref, placeholder: loading ? "Loading..." : other.placeholder, searchable: true, disabled: loading, rightSection: loading ? _jsx(Loader, { size: "1rem" }) : null, comboboxProps: { onOpen: fetchData, } })); }); AsyncMultiSelect.displayName = "AsyncMultiSelect"; export default AsyncMultiSelect;