Я пытался получить данные и сохранить их в состоянии, а затем, когда я выбрал один из параметров в раскрывающемся списке, я не смог сохранить их в переменной и отправить их обратно в базу данных по нажатию кнопки отправки. Может кто-нибудь может помочь мне, как это сделать?
//fetches the data from an api and maps to dropdown
componentDidMount() {
let initialPlanets = [];
fetch('http://b0499a61.ngrok.io/api/assetType')
.then(response => {
return response.json();
}).then(data => {
initialPlanets = data.map((planet) => {
return planet
});
console.log(initialPlanets);
this.setState({
planets: initialPlanets,
});
});
}
render() {
return (
<div id="react-search">
<Options state={this.state}/>
</div>
)
}
}
//mapping with dropdown
let planets = this.props.state.planets;
let optionItems = planets.map((planet) =>
<option key={planet.asset_type}>{planet.asset_type}
</option>
);
return (
<div>
<select>
{optionItems}
</select>
</div>
)
}
}
//here need to store the selected dropdown data in a variable
class Requestbutton extends React.Component {
constructor(props) {
super(props);
this.state = {
items:[],
emp_id:'',
asset_type: "",
comments_emp: ""
};
onChange(e) {
this.setState({
[e.target.name] : e.target.value });
}
componentDidMount(){
var p_id=localStorage.getItem('id')
fetch(`http://b0499a61.ngrok.io/api/employee/${p_id}`)
.then(res => res.json())
.then(json => {
this.setState({
isLoaded : true,
items: json[0],
})
console.log(this.state.items)
});
}
onSubmit(e){
e.preventDefault();
const newpost ={
emp_id : this.state.items.emp_id,
asset_type : this.state.asset_type,
comment_emp: this.state.comment_emp
}
console.log(newpost)
fetch('http://b0499a61.ngrok.io/api/newAssetRequest',{
method: 'POST',
headers: {
'content-type' : 'application/json'
},
body: JSON.stringify(newpost)
})
.then(res => res.json())
.then(data => console.log(data));
}
render() {
return(
<label>Select Asset type</label>
<Dropdown />
}
}
Я ожидал отправить выбранную опцию из выпадающего списка на сервер.