Jan Mackovic
Jan Mackovic

Reputation: 1

How do I fetch the data from the API? I always get Undefined

I'm practising React with a small project where I want to display some Nba players but I don't get any data when trying to map an object. I'm using this Api: http://data.nba.net/prod/v1/2022/players.json

Here is the code:


import React, { useEffect, useState } from "react";

const Players = () => {
  const url = "http://data.nba.net/prod/v1/2022/players.json";
  const [players, setPlayers] = useState([]);

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

  const getPlayers = async () => {
    const api = await fetch(url);
    const data = await api.json();
    //wrapping a object into a array
    setPlayers([data].flat());
  };
  return (
    <div>
      <h3>Sacramento player info</h3>
      <ul>
        {players.map((player) => (
          <li key={player.league.sacramento.id}>
            {player.league.sacramento.firstName}{" "}
            {player.league.sacramento.lastName}{" "}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Players;

Upvotes: 0

Views: 204

Answers (1)

DINK74
DINK74

Reputation: 547

I recreated your code on codesandbox and it works just fine. I use other approach on getting data thru fetch and changed http:// to https://

const Players = () => {
  const [data, setData] = useState(null);

  function getAPIData() {
    fetch("https://data.nba.net/prod/v1/2022/players.json")
      .then((response) => {
        if (response.ok) {
          return response.json();
        }
        throw new Error("ERROR (response not ok)");
      })
      .then((data) => {
        setData(data);
      })
      .catch((response) => {
        console.log("error");
      });
  }

  useEffect(() => getAPIData(), []);

  return (
    data && (
      <div>
        <h3>Sacramento player info</h3>
        <ol>
          {data.league.sacramento.map((player) => (
            <li key={player.personId}>
              {player.firstName} {player.lastName}
            </li>
          ))}
        </ol>
      </div>
    )
  );
};

working code: https://codesandbox.io/s/players-info-51gf1w

Upvotes: 1

Related Questions