*****My code *****
import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';
import axios from 'axios';
export default class App extends Component {
state = {
arraydata: []
};
componentDidMount = () => {
this.getmongodbdata(); }
getmongodbdata = () => {
axios.get('http://localhost:8080/fetch').then(res => {
console.log(res.data,)
console.log('Data is recieved')
this.setState({arraydata: res.data})
})
.catch(() => {
alert('Sorry, could not able to fetch the data');
}) }
render() {
return (
<div className="Main">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to Future</h1>
</header>
<h1> hello world</h1>
<ul key={'qw'}>
{this.state.arraydata.map((data, index) => {
return <li key={`ui-${index}`}>
{data._id}
</li>
})}
</ul>
</div>
) } }
* Screenshot for better understanding
At the moment I'm getting the id from the data by doing:
<ul key={'qw'}>
{this.state.arraydata.map((data, index) => {
return <li key={`ui-${index}`}>
{data._id}
</li>
})}
</ul>
***What i want to get *** is to get inside the data.site.alerts.alert
(show the alert column)
for that I'm trying to do
<ul key={'qw'}>
{this.state.arraydata.map((data, index) => {
return <li key={`ui-${index}`}>
{data._id}
<ul key={`alert-ui-${index}`}>
{data.site.alerts.map((alertData, alertIndex)=>{
return <li key={`alert-li-${alertIndex}`}>{alertData.alert}</li>
});
</ul>
</li>
})}
</ul>
but getting error map cannot use property that is not undefined.
I often find that react throws errors even when the data mapped over is not undefined, so a lot of times you just have to use some inline conditional like @prasanth said:
<ul key={'qw'}>
{this.state.arraydata?.map((data, index) => {
return <li key={`ui-${index}`}>
{data._id}
<ul key={`alert-ui-${index}`}>
{data.site.alerts.map((alertData, alertIndex)=>{
return <li key={`alert-li-${alertIndex}`}>{alertData.alert}</li>
});
</ul>
</li>
})}
</ul>
or
<ul key={'qw'}>
{this.state.arraydata ? this.state.arraydata.map((data, index) => {
return <li key={`ui-${index}`}>
{data._id}
<ul key={`alert-ui-${index}`}>
{data.site.alerts.map((alertData, alertIndex)=>{
return <li key={`alert-li-${alertIndex}`}>{alertData.alert}</li>
}) : /* say something */;
</ul>
</li>
})}
</ul>
or something along those lines.
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.