MCPcopy Create free account
hub / github.com/dailydotdev/apps / Autocomplete

Function Autocomplete

packages/shared/src/components/fields/Autocomplete.tsx:28–171  ·  view source on GitHub ↗
({
  name,
  isLoading,
  options,
  label,
  onChange,
  onSelect,
  onBlur: onBlurProp,
  selectedValue,
  defaultValue,
  resetOnBlur = true,
  ...restProps
}: AutocompleteProps)

Source from the content-addressed store, hash-verified

26}
27
28const Autocomplete = ({
29 name,
30 isLoading,
31 options,
32 label,
33 onChange,
34 onSelect,
35 onBlur: onBlurProp,
36 selectedValue,
37 defaultValue,
38 resetOnBlur = true,
39 ...restProps
40}: AutocompleteProps) => {
41 const [input, setInput] = useState(defaultValue || '');
42 const [isFocused, setIsFocused] = useState(false);
43 const inputRef = useRef<HTMLInputElement | null>(null);
44 const [selectedOption, setSelectedOption] = useState<
45 AutocompleteOption | undefined
46 >(undefined);
47
48 /*
49 To prevent flickering of the selected option image as the user types.
50 We want to set the selected option only when the selected value changes or the user clears the selected value.
51 */
52 useEffect(() => {
53 if (!selectedValue) {
54 setSelectedOption(undefined);
55 return;
56 }
57 if (selectedOption?.value !== selectedValue) {
58 setSelectedOption(options.find((opt) => opt.value === selectedValue));
59 }
60 }, [selectedValue, options, selectedOption]);
61
62 const handleChange = (val: string) => {
63 setInput(val);
64 onChange(val);
65 };
66
67 const handleSelect = (opt: AutocompleteOption) => {
68 setInput(opt.label);
69 onSelect(opt.value);
70 setIsFocused(false);
71 inputRef.current?.focus();
72 };
73 const handleBlur = () => {
74 setIsFocused(false);
75 if (resetOnBlur) {
76 setInput(options.find((opt) => opt.value === selectedValue)?.label || '');
77 }
78 onBlurProp?.();
79 };
80
81 const isSecondaryField = restProps.fieldType === 'secondary';
82
83 return (
84 <div className="flex flex-col gap-2">
85 {!isSecondaryField && (

Callers

nothing calls this directly

Calls 2

handleChangeFunction · 0.70
handleSelectFunction · 0.70

Tested by

no test coverage detected