How to access properties of an object within another object in Reactjs

Asked

Viewed 1,381 times

1

I am consuming via Xios the following JSON: https://randomuser.me/api/? Results=5

When I try to access person.name.title I get the following error:

TypeError: Cannot read property 'title' of undefined

I can only access the title property when I type like this {pessoa.name && pessoa.name.title,

Can someone explain to me why?

import React, {Component} from 'react';
import {Card, Col, Button} from 'react-bootstrap';
import api from "../../services/api"

class CardPeople extends Component {
    constructor(props){  
        super(props)  
        this.state = { 
            pessoas: [
                {    
                }
            ]
        }
    }
    async componentDidMount(){
        const people_api = await api.get("https://randomuser.me/api/?results=5");           
        this.setState({
            pessoas: people_api.data.results
        })
    }
    render() {
        return (
            <>
             {this.state.pessoas.map((pessoa, index) =>
            <Col key={pessoa.gender}>                               
                <p> {pessoa.name && pessoa.name.title}</p><br></br>                 
            </Col>
            )}
            </>
        )
    }
} 

1 answer

2


By checking your code I discovered that the array of pessoas with an empty object, observe:

this.state = { 
    pessoas: [
        { // <-- aqui o problema
        } // <-- aqui o problema
    ]
}

but in the case as it has no items in the array (items that will be loaded after the component is fully loaded), just need to inform for the script which is a array no item (with size 0), example:

this.state = { 
    pessoas: [] //correto
}

that is, how the array with an object without keys and values, cause at the beginning of the loading of that component the exception as demonstrated in your question for lack of information that is only available from the request.


I ended up simulating an example and in my case it worked perfectly, example:

class Source extends React.Component {
  constructor() {
    super();
    this.state = {
      results: []
    };
    this.getResults =
      this.getResults.bind(this);
  }
  
  componentDidMount(){
     this.getResults();
  }
  
  getResults() {
    fetch('https://randomuser.me/api/?results=5')
      .then(r => r.json())
      .then(r => {
        this.setState({results: r.results});
      });
  }
  
  render() {
    return (
      <div>
        <ul>
          {this.state.results.map((p,i) => <li key={i}>{p.name.title}</li>)}
        </ul>
      </div>
    );
  }
}
ReactDOM.render( <Source/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

The above example was actually to demonstrate how it works, it only differs that a proper API was used from to seek information on url but, the problem is actually how it was explained only make change by removing the empty object from the array that your code will work.

  • 1

    It was just that, it worked perfectly, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.