So for the practice I am trying to consume rest point with react framework. But somehow I getting error like:
TypeError: Cannot read property 'map' of undefined
Json look like this:
{
"name":"sadasd.tx",
"application":"Word",
"id":"123",
"type":"Mixed",
"containers":[
"Variant1",
"Variant2_sch",
"Variant5",
"Variant6",
"Variant3",
"Variant4"
]
}
React component looks like this:
class ContainerList extends React.Component{
constructor(props){
super(props);
this.state={fileContent: []};
}
componentDidMount(){
fetch('http://localhost:8080/'+ this.props.file)
.then(res => res.json())
.then((data) => {
this.setState({fileContent: data})
})
}
render() {
const containerNames = this.state.fileContent.containers.map(container => <Container containerName={container} />);
return (
<table>
<tbody>
{containerNames}
</tbody>
</table>
)
}
}
After removing map over array and debugging in browser I see that json object is correctly assigned to the variable. But when iterating over it I getting undefined error. Anyone has idea what might be wrong?
[EDIT] I am completely does not understand this. I did understand why does it throwing this error, after your posts guys. But I did something like this after reading your answers:
I added to state another variable isLoading with default true value. And in fetch after getting json I set it to false.
fetch('http://localhost:8080/'+ this.props.xx)
.then(res => res.json())
.then((data) => {
this.setState({fileContent: data, isLoading: false})
})
and in render method I did add if statement:
render() {
let containerNames;
if(this.state.isLoading){
containerNames = <h1>Loading</h1>
}else{
containerNames = this.state.fileContent.listContainers.map(listContainer => <Container listContainerName={listContainer} />);
}
return (
<table>
<tbody>
{containerNames}
</tbody>
</table>
)
So it should not be possible to enter else statemend before fetchind data. But react is somehow doing this. And throwing error.
render()is called before thefetch()completes, thatfileContentobject will be empty.