I'm still new to ReactJS and I'm currently fiddling around with Spotify API and it works great but I stumbled into an issue whilst trying to render an array of images that were retrieved via the API.
At first, I tried calling it inside the render() component but it only produces a list of empty 'undefined' images with only the alt attribute showing up. Secondly, I tried it inside return()and just has the same symptom as the former, this time without any of the images at all.
This issue only occurs however when I try using the .map() method; when I render an image individually, it works just fine.
import React, { Component } from "react";
let someData = "hello";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
playlists: { name: [], plist_id: [], albumArt: [] }
};
}
getPlaylists(someData) {
let plistNames = [];
let plistContents = [];
let plistArts = [];
someApi
.searchPlaylists(someData)
.then(data => {
if (data.playlists.items) {
if (data.playlists.items.length > 0) {
console.log(data);
data.playlists.items.forEach(plist => {
plistNames.push(plist.name);
plistContents.push(plist.id);
plistArts.push(plist.images[0].url);
this.setState({
playlists: {
name: plistNames,
plist_id: plistContents,
albumArt: plistArts
}
});
});
}
}
})
.catch(err => {
console.error(err);
});
}
render() {
//Produces a list of empty images with only the alt attribute showing up
let _playlists = this.state.playlists.albumArt.map((plist, index) => {
return <img key={index} src={plist.albumArt} alt="Album Art"/>
})
return (
<div className="App">
<button onClick={() => this.getPlaylists(someData)}>
Get Playlist
</button>
{_playlists}
{/* THIS PRODUCES a similar sympton as the former
{playlists.albumArt.map((plist, index) => {
<img key={index} src={plist.albumArt} alt="Album Art"/>
})
} */}
{/* THIS IMAGE RENDERS THE FIRST ELEMENT FROM THE ARRAY AND WORKS FINE
<img src={playlists.albumArt[0]}/> */}
</div>
);
}
}
How does one tackle an issue like this? Thanks a mil for your time and help.
<img key={index} src={plist.albumArt} alt="Album Art"/>suffice as it's already in an image tag?