React returns “Cannot read property “name” of undefined.” (Fetch API) [closed]

I’ve been trying to build a react app that fetches a random persons dataset from an api using fetch. When trying to output the data – 7 out of 10 times it returns “TypeError: Cannot read property ‘name’ of undefined”. Somehow (I guess because of Strict Mode) – the function always gets called twice. The first time it almost always returns undefined which I guess is screwing the process up.

I’m very much a beginner in all things related to coding – so I’d love to know how to pinpoint the problem & what I can do to fix it.

function App() {
  const url = "https://randomuser.me/api/";

  const [person, setPerson] = useState();

  const getPerson = async () => {
    const response = await fetch(url);
    const data = await response.json();
    const person = data.results[0];
    const { title, first, last } = person.name;
    const { age, date } = person.dob;
    const { country, city, postcode } = person.location;
    const { name, number } = person.location.street;
    const { phone, email } = person;

    const newPerson = {
      name: title + " " + first + " " + last,
      dob: age + ", " + date,
      street: name + number,
      location: city + " " + postcode,
      country: country,
      phone: phone,
      email: email,
      picture: person.picture.large,
    };

    setPerson(newPerson);
  };

  useEffect(() => {
    getPerson();
  }, []);

  return (
    <Container>
      <Header />
      <Main>
        <Card>
          <CardHeader />
          <CardInnerContainer data={person} />
          <CardFooter />
        </Card>
      </Main>
      <Footer />
    </Container>
  );
}

export default App;
const CardInnerContainer = (props) => {

  return (
    <div className="card-inner-container">
      <div className="card-applicant-container">
        <p className="name">{props.person.name}</p>
        <p className="dob-age">{props.person.dob}</p>
        <p className="street">{props.person.street}</p>
        <p className="location">{props.person.location}</p>
        <p className="country">{props.person.country}</p>
        <p className="phone">{props.person.phone}</p>
        <p className="email">{props.person.email}</p>
      </div>
    </div>
  );
};

export default CardInnerContainer;

Error message:

TypeError: Cannot read property 'name' of undefined
CardInnerContainer

   4 | return (
   5 |   <div className="card-inner-container">
   6 |     <div className="card-applicant-container">
>  7 |       <p className="name">{props.person.name}</p>
     | ^   8 |       <p className="dob-age">{props.person.dob}</p>
   9 |       <p className="street">{props.person.street}</p>
  10 |       <p className="location">{props.person.location}</p>

Answer

You need to conditionally render the component that takes person as a prop.

       { person && <CardInnerContainer data={person} /> }

like this. So it can be rendered after you fetched and set the person.