I am taking my first steps with React and got stuck on this error:
"Uncaught (in promise) TypeError: Cannot read property 'map' of undefined at Region.render (Region.js:52)"
The file in question looks like this:
import React, { Component } from 'react';
import 'whatwg-fetch';
import {
Link
} from 'react-router-dom';
class Region extends Component {
constructor(props) {
super(props);
this.state = {
region: [],
error: false,
}
}
componentDidMount() {
const id = this.props.match.params.area_id;
this.fetchData(id);
}
fetchData(id) {
fetch('http://localhost:5000/api/area_id/'+id)
.then(response => response.json())
.then((data) => {
console.log('data', data);
this.setState({
region: data.objects,
});
})
.catch((err) => {
console.log('villa', err)
this.setState({
error: true,
})
});
}
render() {
const { region, error } = this.state;
console.log(region);
const list = region.map((region) => { //THIS IS LINE 52
const link = '/region/' + region.id + '/farm/' +region.farm_id;
return (
<li key={region.farm_id}><Link to={link}>Area:
{region.area_name} - <bold>Farm:</bold>{region.farm_name} </Link></li>
);
})
return (
<div>
<h2>Region</h2>
<br/>
{error ? (<p>Error getting data!</p>) : null}
<ul className="link-list">
{list}
</ul>
<Link to="/">Back</Link>
</div>
);
}
}
export default Region;
And the API at "http://localhost:5000/api/area_id" looks like this:
{
"num_results": 7,
"objects": [
{
"area_id": 1,
"area_name": "\u00c1shreppur",
"farms": [
{
"area_id": 1,
"area_name": "\u00c1shreppur",
"farm_id": 1,
"farm_name": "HVAMMUR"
},
{
"area_id": 1,
"area_name": "\u00c1shreppur",
"farm_id": 2,
"farm_name": "HVAMMKOT"
},
.....
To add some more details, I can tell you that this is the first edition of a history of a certain area and who lived where and when. So there are 7 areas, each area has farms on it, and each farm has a recored of names and years about who used to live at some point.
So the first page loads. I get up a list of 7 area links. When pressing one of the links I get this error. After I get through this, I want to be able to click any one of the farms to get the list of habitants on that farm and the years they lived there.