I am trying to load pictures from jsonPlaceholder. When I console.log out the images array, it works successfully. The moment I try to call the URL from the element, it throws a TypeError. I tried to do it the asynchronous way, even this doesn't work. Is there any workaround for this? What possibly is the problem?
import React, {Component} from 'react';
import axios from 'axios';
class Home extends Component{
state = {
posts : [],
images : []
};
componentDidMount = async () => {
const res = await axios.get('https://jsonplaceholder.typicode.com/posts');
this.setState({posts: res.data.slice(0,10)})
const res2 = await axios.get('https://jsonplaceholder.typicode.com/photos');
this.setState({images: res2.data.slice(0,10)})
}
render = () => {
const {posts} = this.state.posts;
const {images} = this.state.images;
const PostList = this.state.posts.length ? (
this.state.posts.map((post,index) => {
return(
<div className = "post card" key = {post.id}>
<div className = "card-content">
<div className = "card-title">
{post.title}
</div>
<div className>
{(this.state.images[index].url)} //console.log(this.state.images[index] works, but .URL doesn't
</div>
<div>
<p>{post.body}</p>
</div>
</div>
</div>
)
})) : (<div className = "center">No Posts!</div> )
return(
<div className = "container">
<div className = "center">
{PostList}
</div>
</div>)
}
}
export default Home;