React: Uncaught (in promise) TypeError: Cannot read the 'map' property from undefined

I am taking the first steps using React and stuck in this error:

"Unprepared (in promise) TypeError: Unable to read the 'map' property from undefined in Region.render (Region.js: 52)"

The corresponding file is as follows:

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 in http: // localhost: 5000 / api / area_id "is as follows:

{
  "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 more details, I can tell you that this is the first edition of the history of a certain area and who lived where and when. Thus, there are 7 regions, on each territory there are farms, and each farm has names and years about which he used to live.

, . 7 . . , , , , , .

+4

Source: https://habr.com/ru/post/1682834/


All Articles