I am pretty novice to front-end tasks and I am trying to add few dropdowns to my exisitng React
JS code. What I want it is that at event execution, pass the selected dropdown values of these along with exisitng paramters to my FastAPI
backend and somehow it comes up empty or undefined.
Here's my JS code:
import "./App.css";
import React, { useState, useRef, useEffect } from "react";
function App() {
/* few other const variables */
const [isDropdownOpen, setDropdownOpen] = useState(false);
const [validationError, setValidationError] = useState(false);
let text = "";
const [MultiOption1, setMultiOption1] = useState('');
const [MultiOption2, setMultiOption2] = useState('');
const OptionChange1 = (event) => {
setMultiOption1(event.target.value);
};
const OptionChange2 = (event) => {
setMultiOption2(event.target.value);
};
function EnterPress(event) {
if (event.target.value) {
setValidationError(false);
text = event.target.value;
if (event.keyCode === 13) {
display(event.target.value,MultiOption1,MultiOption2);
event.target.value = "";
}
}
else{
if (event.keyCode === 13) {
setValidationError(true);
}
}
}
const submit = async () => {
text = document.getElementById("text").value;
if (text) {
display(text);
text = "";
document.getElementById("text").value = "";
}
else {
setValidationError(true);
}
};
async function display(text,MultiOption1, MultiOption2) {
let response = ""
await fetch(`http://0.0.0.0:80/route?MultiOption1=${MultiOption1}&MultiOption2=${MultiOption2}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: ""
}).then(resp => resp.json()).then(data => {
console.log("data...", data);
response = data;
})
};
return (
<>
<div className="divBlock ff">
<div className="app-container">
<div className="left-panel">
<label htmlFor="dropdown1">Dropdown 1:</label>
<select id="dropdown1" value={MultiOption1} onChange={OptionChange1}>
<option value="Option1">Option 1</option>
<option value="Option2">Option 2</option>
<option value="Option3">Option 3</option>
</select>
<label htmlFor="dropdown2">Dropdown 2:</label>
<select id="dropdown2" value={MultiOption2} onChange={OptionChange2}>
<option value="OptionA">Option A</option>
<option value="OptionB">Option B</option>
</select>
</div>
<div className="Block">
/*Additional div elements */
<div className="text-field" onClick={EnterPress}>
<input
type="text"
id="text"
className={validationError ? 'errorText' : 'text'}
onKeyDown={EnterPress}
/>
<button onClick={submit} className="arrowButton">
<ion-icon className="arrow" name="send"></ion-icon>
</button>
</div>
</div>
</div >
</div>
</>
);
}
export default App;
My Fast API function call looks like this:
@app.post("/route")
def ask(MultiOption1: str = None, MultiOption2: str = None):
I know the issue is that somewhere I am missing some code or function call or settign the values properly at event trigger, but I am unable to get the values passed properly to my Fast API. It comes as empty string