Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

339
Visualizações
Uncaught TypeError: Cannot read properties of undefined (reading 'map')

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

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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>
    );
  }
}
about 4 years ago · Santiago Trujillo Relatório

0

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.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda