Home > Mobile >  Uncaught TypeError: equipo.data is undefined using React
Uncaught TypeError: equipo.data is undefined using React

Time:02-12

I have the following problem trying to traverse an array of objects and I don't know where the problem is.

import './App.css';
import React from 'react';

function App() {

  const [equipo, setEquipo] = React.useState([]);

  // Constructor
  React.useEffect(() => {
    document.title = "Magic - React";
    obtenerDatos();
  }, []);

  // Metodo que recoge info de una Api
  const obtenerDatos = async () => {
    const data = await fetch("https://api.scryfall.com/cards/search?order=set&q=e:ugin&unique=prints");
    const info = await data.json();
    setEquipo(info);
  };

  return (
    <div className="App">
      <ul>
        {equipo.data.map((item) => (
          <li>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Here is the JSON Api where I search the info.

https://api.scryfall.com/cards/search?order=set&q=e:ugin&unique=prints

I try to show the images and the text of the cards in the HTML. I am new with React. Please help and thanks.

CodePudding user response:

Try this:

return (
    <div className="App">
      <ul>
        {equipo?.data?.map((item) => (
          <li>{item.name}</li>
        ))}
      </ul>
    </div>
  );

CodePudding user response:

This is your issue:

const [equipo, setEquipo] = React.useState([]);

On the first render, before the API call has returned, you're attempting to access the .data field of an empty array. Instead, you need to initialize equipo with:

const [equipo, setEquipo] = React.useState({data: []});
  • Related