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

Function Autocomplete

packages/shared/src/components/fields/Autocomplete.tsx:26–163  ·  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

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

Callers

nothing calls this directly

Calls 2

handleChangeFunction · 0.70
handleSelectFunction · 0.70

Tested by

no test coverage detected