Escribí una función para obtener datos de la API de Hacker News con los métodos fetch y .then. Eso funcionó, pero me gustaría aprender a usar el método async/await. Por alguna razón, la última búsqueda dentro del bucle forEach devuelve undefined. ¿Algúna idea de cómo arreglar esto?
Aquí está el código original:
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] }) }) }) }) }Aquí está la nueva versión:
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] }) }Intenté agregar asíncronos y esperas en todo el bucle forEach, pero no funcionó. También traté de convertirlo a for of loop, pero obtuve el mismo resultado (indefinido).
¡Muchas gracias por adelantado!
Editado: resuelto esto, aquí está la versión de trabajo:
// 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] }) } }