I need to display JSON data that is coming from webapi. I need to fill dropdown with the data in REACT. I am getting the issue while filling the data in .
console.log(this.state.Templatelist) returns the data. this data is coming from api.
[{"Template_ID":11,"TemplateName":"All"},{"Template_ID":21,"TemplateName":"Test"}]
Please find my code:
import React from "react";
export class test extends React.Component {
constructor(props) {
super(props);
this.state = {
CopyFromTemplate_ID: "",
Templatelist: [],
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ CopyFromTemplate_ID: event.target.value });
console.log(event.target.value)
}
componentDidMount() {
this.getTemplateList();
}
getTemplateList() {
fetch(REQUEST_URL)
.then(response => response.json())
.then((data) => {
this.setState({
Templatelist: data,
loading: false
})
console.log(this.state.Templatelist);
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit} >
{this.state.Templatelist}
<select size="1" value={this.state.CopyFromTemplate_ID} onChange={this.handleChange} >
<option></option>
{this.state.Templatelist.map((item) =>
<option id={item.Template_ID} value={item.Template_ID}>
{item.value}
</option>)
}
</select>
</form>
</div>
);
}
}
export default test;
Thanks
Since your data is undefined or waiting to arrive, you need to check if it is an array before you render it. You can check if data arrived and if it has a length, if not, then render the loading component.
{this.state.Templatelist.length? this.state.Template.map((item) =>
<option id={item.Template_ID} value={item.Template_ID}>
{item.value}
</option>) : <p>...loading</p>
}