Reputation: 221
I have fetch the data from an API and trying to loop through the json data which I have received from URL, But I ma getting error and it says 'posts.map is not a function. I have looked through internet but could not received the answer I am looking for. Appreciate your help!
here is my reactjs code:
class App extends React.Component {
state = {
isLoading: true,
posts: [],
error: null,
users: []
}
async componentDidMount(){
const URL_API = `https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json`;
const response = await fetch(URL_API);
const data = await response.json(); //this is asyncronous calls that
return us the json data
this.setState({
posts: data,
isLoading: false,
})
}
render() {
const { posts } = this.state
console.log('posttt', posts);
return (
<React.Fragment>
<h1>React fetch - Blog</h1>
<hr />
<ul id='list'>
{posts.map(post => (
<li
key={post.id}>
<span>{post.title}</span>
<span>{post.content}</span>
</li>
))}
</ul>
</React.Fragment>
);
}
}
export default App;
]1
Upvotes: 0
Views: 114
Reputation: 31024
It seems that the data returned from the API is an object with a posts
key.
So either set the state with data.posts
or loop over posts.posts
.
The first option seems more reasonable in my opinion.
this.setState({
posts: data.posts,
isLoading: false,
})
Upvotes: 1