Reputation: 29
I'm new to react. I create a form which consist with input fields, button and drop-down menu. It's is a functional component. I need to pass selected drop-down items' id to back-end through axios with other form value. Before create drop-down other values that get from input fields could add pass to backend. Is there any way to pass values to back-end with other form input values? Here is my code.
const [course, setCourse] = useState({
name: "",
code: "",
passMark: "",
lic: "",
subjects: [],
options: []
});
//const [subject, setSubject] = useState();
async function getSubjects(){
const res = await axios.get("http://localhost:3000/subject")
const data = res.data
const option = data.map((item)=>({
"value" : item._id,
"label" : item.name
}))
setCourse({options: option})
}
/*function handleSelect(event){
setSubject(event.target.value)
}*/
function handleClick(){
axios.post("http://localhost:3000/course/add",course).then((res)=>{
console.log(res);
}).catch((err)=>{
console.log(err);
})
}
return (
<Form.Group className="mb-3" >
<Form.Label>Subjects</Form.Label>
<Select options={course.options} name="subjects" isMulti />
</Form.Group>
</Form>
</div>
</div>
)
Upvotes: 0
Views: 2330
Reputation: 5497
You need to attach the value
and onChange
prop to the Select as you are doing for the other Input's as well . Also you need to separate out the options
from your course else while posting you will send that as well.
So create a new state for subject options
const [course, setCourse] = useState({
name: "",
code: "",
passMark: "",
lic: "",
subjects: [],
});
const [ options, setOptions ] = useState(null);
async function getSubjects(){
const { data } = await axios.get("http://localhost:3000/subject")
const option = data.map((item)=>({
"value" : item._id,
"label" : item.name
}))
setOptions (options)
}
And add the value
and onChange
prop for your select
<Select
options={options}
name="subjects"
isMulti
value={course.subjects}
onChange={(selectedValues) => {
setCourse((preValue) => {
return {
...preValue,
subjects: selectedValues,
};
});
}}
/>
To send only subject Id's
function handleClick() {
const requestData = {
...course,
subjects: course.subjects.map((subject) => subject._id),
};
axios
.post("http://localhost:3000/course/add", requestData)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}
Upvotes: 1