React won't render elements in map function

Issue

I’m trying to render elements from a map function however it does not seem to be working. I have tried to change the return but nothing seems to work.

class API extends Component {
  myTop10Artists() {
    Api.getMyTopArtists(function (err, data) {
      if (err) {
        console.error(err);
      } else {
        console.log(data.items);
        return data.items.map((artist) => {
          console.log("artist name " + artist.name);
          console.log("artist id " + artist.id);
          console.log("artist popularity " + artist.popularity);
          return (
            <div key={artist.id} className="card">
              <div key={artist.id} className="cardContent">
                <h3> {artist.name} </h3>{" "}
              </div>{" "}
            </div>
          );
        });
      }
    });
  }
  render() {
    return <div className="cardsWrap"> {this.myTop10Artists()} </div>;
  }
}

Solution

Just an idea of how to do approach this another way with hooks and functional components. Main issue in your code, as mentioned by others already, is the fact that the results are not returned by the callback or set to a state.

const MyTop10Artists = () => {
  const [artists, setArtists] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState();

  useEffect(() => {
    Api.getMyTopArtists((err, data) => {
      if (err) {
        console.error(err);
        setError(err);
        return;
      }
      setArtists(data.items);
      setIsLoading(false);
    });
  }, []);

  return (
    <>
      {isLoading && "Loading"}
      {error && error}
      {!isLoading && artists.length === 0 && "No artists"}
      {!isLoading &&
        artists.map((artist) => (
          <div key={artist.id} className="card">
            <div key={artist.id} className="cardContent">
              <h3>{artist.name}</h3>
            </div>
          </div>
        ))}
    </>
  );
};

const API = () => (
  <div className="cardsWrap">
    <MyTop10Artists />
  </div>
);

Answered By – Julian Kleine

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published