'React JS selector with fetch
When I take data from this form via fetch by name for selector, I get id=1 or 2 in the data transfer, but I want to get name ="Name1" or "Name2". It works with regular forms, but not with the selector
type Service = {
id: number,
name: string,
}
const serviceList: Service[] = [
{
id: 1,
name: 'Name1',
},
{
id: 2,
name: 'Name2',
}
const [curIdService, setСurIdService] = useState(0)
async function post(event) {
event.preventDefault()
const serviceName = event.target.curIdService.value
const res = await fetch('urlApi', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ serviceName })
})
if (res.ok) {
const result = await res.json()
console.log(result);
}
}
return (
<>
<form id="submit-form" onSubmit={post}>
<select className="selectModel" value={curIdService} name="curIdService" onChange={event =>
setСurIdService(+event.target.value)} >
<option value={0} selected disabled>Выберите вид услуг</option>{serviceList.map(service =>
<option key={service.id} value={service.id}>{service.name}</option>)}
</select>
</form>
</>
Solution 1:[1]
In your form you're passing allong service.id:
<option key={service.id} value={service.id}>{service.name}</option>
Change it to
<option key={service.id} value={service.name}>{service.name}</option>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | crevulus |
