May 5, 2022
0
Level 2
Custom <SelectSearch /> component not populating data - Inertia with React
I have been trying to populate a headlessui form Combobox component with records from a database. when I console.log(options), I get the array. But the data is not displayed in the component.
This is in the Create.js page:
const { customers } = usePage().props;
const options = [
customers.map((customer, index) => ({
key: index,
id: customer.id,
name: customer.first_name + " " + customer.last_name,
})),
];
This is the SelectSearch headlessui component:
export default function SelectSearch({
value,
onChange,
options,
label,
valKey,
className,
id,
name,
}) {
const [query, setQuery] = useState("");
const filteredOptions =
query === ""
? options
: options.filter((option) =>
option[label]
.toLowerCase()
.replace(/\s+/g, "")
.includes(query.toLowerCase().replace(/\s+/g, ""))
);
return (
<>
<Combobox value={value} onChange={onChange} name={name} id={id}>
<div className="relative mt-1">
<div>
<Combobox.Input
displayValue={(option) =>
option[label] ?? `Select an option...`
}
onChange={(e) => setQuery(e.target.value)}
/>
<Combobox.Button className="absolute inset-y-0 right-0 flex items-center pr-2">
<SelectorIcon
className="h-5 w-5 text-gray-400"
aria-hidden="true"
/>
</Combobox.Button>
</div>
<Transition
as={Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
afterLeave={() => setQuery("")}
>
<Combobox.Options>
{filteredOptions.length === 0 && query !== "" ? (
<div>
Nothing found.
</div>
) : (
filteredOptions.map((option) => (
<Combobox.Option
key={option[valKey]}
className={({ active }) =>
`relative cursor-default select-none py-2 pl-5 pr-4 ${
active
? "bg-indigo-600 text-white"
: "text-gray-900"
}`
}
value={option}
>
{({ value, active }) => (
<>
<span
className={`block truncate ${
value
? "font-medium"
: "font-normal"
}`}
>
{option[label]}
</span>
{value ? (
<span
className={`absolute inset-y-0 left-0 flex items-center pl-3 ${
active
? "text-white"
: "text-indigo-600"
}`}
>
{/* <CheckIcon
className="h-5 w-5"
aria-hidden="true"
/> */}
</span>
) : null}
</>
)}
</Combobox.Option>
))
)}
</Combobox.Options>
</Transition>
</div>
</Combobox>
</>
);
}
The SelectSearch component is empty, despite the data being called from the database. When I try to search for records in the component, I get this error: Cannot read properties of undefined (reading 'toLowerCase'). I'm stuck with this. Any help guys?
Please or to participate in this conversation.