본문 바로가기

카테고리 없음

Debounce + MultiSelect + Async Select (react-select)

// debounce
export const debounce = (func, delay) => {
	let timeoutId;
	return function (...args) {
		clearTimeout(timeoutId);
		timeoutId = setTimeout(() => {
			func(...args);
		}, delay);
	};
};

// debounce
export function debounceAsync(func, wait) {
	let timeout;

	return async function (...args) {
		const context = this;

		return new Promise((resolve) => {
			clearTimeout(timeout);

			timeout = setTimeout(async () => {
				const result = await func.apply(context, args);
				resolve(result);
			}, wait);
		});
	};
}

 

 

컴포넌트 단

	const debouncedLogin = debounceAsync(async (inputValue) => {
		const data = await getSearchProduct(inputValue);

		const options = data.map((item) => ({
			...item,
			label: `${item.itemName}-${item.sapCode}`,
			value: item.sapCode,
		}));

		return options;
	}, 500);
	const promiseOptions = (inputValue) =>
		new Promise(async (resolve) => {
			try {
				if (inputValue) {
					const options = await debouncedLogin(inputValue);
					resolve(options);
				}
			} catch (error) {
				console.error('Error fetching options:', error);
				resolve([]);
			}
		});
<Controller
    control={control}
    name="gwpCodes"
    render={({ field: { onChange }, formState: { defaultValues } }) => (
        <AsyncSelect
            required
            isMulti
            placeholder="Search GWP Product"
            cacheOptions
            defaultOptions
            loadOptions={promiseOptions}
            onChange={(values) =>
                onChange(values.map((item) => item.sapCode))
            }
        />
    )}
/>