Home > front end >  Cannot read values from array object from the map function in React
Cannot read values from array object from the map function in React

Time:12-18

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;

CodePudding user response:

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.

CodePudding user response:

You are mapping an items array which consists of some item and passing the item in the Titlecard component.

item is an object? If so Titlecard should accept item.otherKey which you have passed through a object prop {item} ?

  • Related