Im using React, Postgres, Node, Express
I have a datalist with an input box, when one of the options from the datalist is selected I need to fire of an event. My problem I believe is I used mappings to map my datalist options, but the button which submits the form is not mapped.
const DataList1 = ({getSupplierContacts2}) => {
const [suppliers, setSuppliers] = useState([]);
//Search query for list of supplier names and their ids
const getSuppliers = async () => {
try {
const response = await fetch("http://localhost:5000/supplier");
const jsonData = await response.json();
setSuppliers(jsonData);
console.log(jsonData);
} catch (err) {
console.log(err.message);
}
}
useEffect(() => {
getSuppliers();
}, []);
return <Fragment>
<form>
<label htmlFor="SupplierDatalistInput">Select Supplier</label>
<input list="SupplierDatalist" name="SupplierDatalistInput" id="SupplierDatalistInput" onSelect={()=> getSupplierContacts2(supplier.supplier_name)}/>
<datalist id="SupplierDatalist">
{suppliers.map(supplier => (
<option key={supplier.supplier_id} value={supplier.supplier_name} />
))}
</datalist>
<input type="submit">
</form>
</Fragment>
}
And here is the method which I need to fire of on a datalist option selection:
const getSupplierContacts2 = async (supplier_name) => {
try {
const response = await fetch(`http://localhost:5000/contact_supplier/${supplier_name}`);
const jsonData = await response.json();
setContacts(jsonData);
} catch (err) {
console.log(err.message);
}
}
Also the route:
//Get entries from contact table from selected supplier name
app.get("/contact_supplier2/:id", async (req, res) => {
try {
const {name} = req.params;
//const contact = await pool.query('SELECT * FROM supplier_contacts WHERE supplier_id = $1 ORDER BY scontact_id ASC', [id]);
const contact = await pool.query(
`SELECT suppliers.supplier_name, supplier_contacts.scontact_name, supplier_contacts.scontact_title
FROM suppliers
LEFT JOIN supplier_contacts ON supplier_contacts.supplier_id = suppliers.supplier_id
WHERE suppliers.supplier_name = $1
ORDER BY scontact_id ASC;`, [name]);
res.json(contact.rows);
} catch (err) {
console.error(err.message);
}
})
To clarify, the datalist and route work as expected, however I get an error
'supplier' is not defined
So my understanding is I need to include the submit button in the mapping, however all I succeeded in doing is for every datalist option I added a submit button. So having a bunch of submit buttons stacked beside each other is not what I want, help much appreciated!