Home > Software engineering >  Uncaught TypeError: Cannot read properties of undefined (reading 'map')
Uncaught TypeError: Cannot read properties of undefined (reading 'map')

Time:12-26

I am getting this error

Mainsection.js:27 Uncaught TypeError: Cannot read properties of undefined (reading 'map')

Here is my mainsection.js file, I am using API key to iterate the data, I am still not getting the cause of the error. First I had made an array whose name was info and stored all the data in it and then iterated it, Now after using fetchapi, I deleted that array as it was of no use. I don't know whether it was meant to delete or not.

import React, { Component } from 'react'
import Card from './Card'

export default class Mainsection extends Component {

    constructor() {
        super();
        this.state = {
            info:null
        }
    }
async componentDidMount(){
    let Url="https://randomuser.me/api/?inc=gender,name,nat,location,picture,email&results=";
    let data= await fetch(Url);
    let parsedData= await data.json()
    console.log(parsedData);
    this.setState({
         info : parsedData.info
    })

}

    render() {
        return (
            <div>
                <div className="container mt-5">
                    <div className="row">
                        {this.state.info.map((element) => {
                            return <div className="col-md-4">
                                <Card key={element.email} name={element.name} location={element.location} gender={element.gender} imageUrl={element.picture.medium} />
                            </div>
                        })}

                    </div>
                </div>
            </div>
        )
    }
}

And here is my card.js file

import React, { Component } from 'react'

export default class Card extends Component {
    render() {
        let {name, location, gender, imageUrl}=this.props
        return (
            <div>
                 <div className="card" style={{ width: "18rem" }}>
            <img src={imageUrl} className="card-img-top" alt="..." />
            <div className="card-body">
                <h5 className="card-title">{name}</h5>
                <p className="card-text">{location}</p>
                <p className="card-text">{gender}</p>
                <a href="/" className="btn btn-primary">Go somewhere</a>
            </div>
        </div>
            </div>
        )
    }
}

Please let me I should provide more details

CodePudding user response:

You can find a working example here: https://codesandbox.io/s/musing-hill-uxtt0

There are other issues with your code. For example, the name and location are objects and you are directly trying to show it on UI. I have also added code to fix name.

Mainsection.js

import React, { Component } from "react";
import Card from "./Card";

export default class Mainsection extends Component {
  constructor() {
    super();
    this.state = {
      info: null,
      results: null
    };
  }
  async componentDidMount() {
    let Url =
      "https://randomuser.me/api/?inc=gender,name,nat,location,picture,email&results=";
    let data = await fetch(Url);
    let parsedData = await data.json();
    console.log(parsedData);
    this.setState({
      info: parsedData.info,
      results: parsedData.results
    });
  }

  render() {
    console.log("results : ", this.state.results);
    return (
      <div>
        <div className="container mt-5">
          <div className="row">
            {this.state?.results?.map((element) => {
              return (
                <div className="col-md-4">
                  <Card
                    key={element.email}
                    name={element.name}
                    location={element.location}
                    gender={element.gender}
                    imageUrl={element.picture.medium}
                  />
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }
}

Card.js

import React, { Component } from "react";

export default class Card extends Component {
  render() {
    let { name, location, gender, imageUrl } = this.props;
    return (
      <div>
        <div className="card" style={{ width: "18rem" }}>
          <img src={imageUrl} className="card-img-top" alt="..." />
          <div className="card-body">
            <h5 className="card-title">{`${name?.title} ${name?.first} ${name?.last}`}</h5>
            <p className="card-text">{JSON.stringify(location)}</p>
            <p className="card-text">{gender}</p>
            <a href="/" className="btn btn-primary">
              Go somewhere
            </a>
          </div>
        </div>
      </div>
    );
  }
}

CodePudding user response:

So, the API you are using doesn't response back with an Array. But it responses with an object, that object has 2 attributes which are results and info. as you can see below

{
"results": ...
....
....
"info": ...
}

and results it self is an Array of objects, while info is just an object.

So yes, you cant use map on object, its only useable on arrays. Check the response carefully so you can decide what you wanna do.

  • Related