Alevel
Alevel

Reputation: 43

Cannot read values from array object from the map function in React

I am trying to pass value from an array items object to another component using map(). All values is coming from api call and is showed in console.But when passing the value from here to Titlecard, I am getting error cannot read properties of undefined map()?I have given the code.Also I have shared Titlecard. Always passing only one record into the array Can anyone guide me here? Thanks

import axios from "axios";
import React, { useEffect, useState } from "react";
import { Container } from "react-bootstrap";
import Titlecard from "./Titlecard";
import { HeroesUrl } from "../apiurl/HeroesApi";
const TitleHero = () => {
  const [items, setItems] = useState([]);
  useEffect(() => {
    axios.get(HeroesUrl).then((response) => {
      setItems(response.data);
      console.log(response.data);
    });
  }, []);
  return (
    <>
      <Container>
        <div>
          {items.map((item) => {
            return (
              <>
                <Titlecard key={item.id} item={item} />
              </>
            );
          })}
        </div>
      </Container>
    </>
  );
};
export default TitleHero;

import React, { useEffect, useState } from "react"; 
const Titlecard = (item) => {
  return (
    <>
      <div> item.firstName </div>
    </>
  );
};

export default Titlecard;

Upvotes: 0

Views: 61

Answers (1)

dor.co
dor.co

Reputation: 43

I edit my answer after I saw you shared Titlecard component. There are 2 problems. The first is in your return, it should be:

<div>{item.firstName}</div>

Because what you return before is just a string like "item.firstName". Second, you have to make a destructuring to the props in Titlecard like:

const Titlecard = ({item}) => {...}

or return:

<div>{item.item.firstName}</div>

The first one is your props name, the second is the prop you pass. So, with using destructuring Titlecard should be like this:

import React from "react"; 
const Titlecard = ({item}) => {
  return (
    <>
      <div>{item.firstName}</div>
    </>
  );
};

export default Titlecard;

Please share Titlecard component code. It's look like that there is a part in the Titlecard component that use the item from the map. In the first time before the axios call finished, the prop item is still empty array, so if you use in the Titlecard component item.something you will get an undefined error. One solution is to add a loader that initial to true, and after the axios call finished set it to false, so if the loader is true, render a loader, else render your map code. Another solution is adding ? when you use item in Titlecard component, like: item?.something, what means only if item is not null or undefined.

Upvotes: 1

Related Questions