I wrote a function fetching data from the Hacker News API with fetch and .then methods. That worked, but I'd like to learn to use the async / await -method. For some reason, the latter fetch within forEach loop returns undefined. Any idea how to fix this?
Here's the original code:
componentDidMount() {
// Get the top 20 post ids
fetch("https://hacker-news.firebaseio.com/v0/beststories.json")
.then(res => res.json())
.then(json => {
let topIds = json.slice(0, 20)
this.setState({
topIds: topIds
})
return topIds
})
// Get the posts based on the ids
.then(ids => {
ids.forEach(id => {
fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
.then(res => res.json())
.then(data => {
let thisPost = data
this.setState({
topPosts: [...this.state.topPosts, thisPost]
})
})
})
})
}
Here's the new version:
async componentDidMount() {
this.getIds()
}
// Get the ID's
async getIds() {
// Get the top 20 post ids
const res = await fetch("https://hacker-news.firebaseio.com/v0/beststories.json")
const json = await res.json()
const topIds = await json.slice(0, 20)
this.setState({
topIds: topIds
})
this.getPosts()
}
// Get the posts
async getPosts() {
const posts = this.state.topIds.forEach(id => {
fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
})
const thisPost = await posts.json() // Posts returnes as undefined
this.setState({
topPosts: [...this.state.topPosts, thisPost]
})
}
I have tried adding both asyncs and awaits to all around the forEach loop, but haven't got it working. I also tried to convert it to for of loop, but got the same (undefined) result.
Thanks a lot in advance!
Edited: resolved this, here's the working version:
// Get the posts
async getPosts() {
for (const id of this.state.topIds) {
const post = await fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
const thisPost = await post.json()
this.setState({
topPosts: [...this.state.topPosts, thisPost]
})
}
}