I am trying to get value of select in React but I get empty value.
<select value={predmet} onChange={(e) => setPredmet(e.target.value)} id="post-name" name="predmet" >
{listaPredmeta.map(({ label, value }) => (
<option id={value} value={value}>
{label}
</option >
))}
</select>
I cant figure out why, I guess it has to do something with map function.
Additional code. Function getData() is inside main component function.
const [listaPredmeta, setlistaPredmeta] =useState([]);
function getData() {
const data = {
IdUniverziteta: parseInt(UserProfile.getUser("uni"), 10),
IdSmera: parseInt(UserProfile.getUser("smer"), 10)
};
const url3 = "https://localhost:44357/api/Fin/Predmet";
axios
.post(url3, data)
.then((result) => {
const predmeti= [];
function predmetSet(item){
const uniData2 = item.split("_");
predmeti.push({
label: uniData2[1],
value: uniData2[0]
})
}
const predmetData = result.data.split(";");
predmetData.forEach(predmetSet);
setlistaPredmeta(predmeti);
});
}
useEffect(() => {
getData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Yeah, so... The problem was in the default value. The code I posted above works perfectly, but it does not have a default value by itself. So I did something not so elegant, but it worked.
const url3 = "https://localhost:44357/api/Fin/Predmet";
axios
.post(url3, data)
.then((result) => {
const predmeti= [];
function predmetSet(item){
const uniData2 = item.split("_");
predmeti.push({
label: uniData2[1],
value: uniData2[0]
})
}
const predmetData = result.data.split(";");
predmetData.forEach(predmetSet);
setlistaPredmeta(predmeti);
});
setPredmet(1); // I SET DEFAULT VALUE IN THIS LINE
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.