end app for woocommerce store, but i have problem rendering the first image of array in
when i console.log(images.src) i see the list of urls of the images, but in img src= it return : TypeError: Cannot read property ‘src’ of undefined
I will be very thankful to help me correctly map the images.
here is my code:
class App extends React.Component {
constructor(props) {
super(props);
this.getPosts = this.getPosts.bind(this);
this.state = {
posts : [],
images: []
};
}
getPosts = async () => {
let res = await api.get("products", {
per_page: 20,
})
let { data } = await res;
this.setState({ posts: data });
}
componentDidMount = async () => {
await this.getPosts();
};
render() {
const { posts } = this.state;
const { images } = this.state
return(
<div>
<Head>
<title>Онлайн магазин KIKI.BG</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<React.Fragment >
{posts.map((posts, index ) => {
{
posts.images.map((images, subindex) =>
console.log(images.src),
<img src={images[0].src} />
)}
return (
<div>
<h1>{posts.name}</h1>
<h2>{posts.price}</h2>
</div>
)})}
</React.Fragment>
</div>
)
}
}
export default App;
3
Answers
well,
console.log(images.src) i see the list of urls of the images
doesn’t make any sense..images
is array. Soimages[0]
should be image with data with propertysrc
on it?. Btw a lot of stuff in this code is just wrong.getPosts
already boundgetPosts
function in constructor (via class property) (getPosts). BTW you dont need to bind is here at all, its not called as a callback.await res
afterapi.get()
… shouldn’t be it justawait api.get()
? Anotherawait
is usually used on fetch, when you do something likeawait response.json()
.key
attributes on element in map, thats wrong. You should put some unique id there (url fe? if not same, or id) for proper component re-render.That would be my code:
if
console.log(images.src)
-> gives list of images.Then,
<img src={images.src[0]}/>
-> should do the trick.may be, Add a null check to be certain.