How do I go about waiting for all the posts to be pushed to the posts array before updating the state?
I had to iterate over an array of post ID's to get the top posts on HackerNews and then turned all those ID's into singular post links and want to store the data from the single post links in an array so I can iterate over that array to render it in the DOM.
import React, {Component} from 'react';
import axios from 'axios';
import Post from './Post';
class ContentWrapper extends Component {
constructor(props){
super(props);
this.state = {
posts: []
}
}
componentDidMount(){
const topStories = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty';
// `https://hacker-news.firebaseio.com/v0/item/.json?print=pretty`
axios(topStories).then(res => {
const posts = [];
res.data.map(val => {
const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`;
return axios.get(url).then(res => {
posts.push(res.data);
}).then(res => this.setState({posts: res}));
});
});
}
render() {
const posts = this.state.posts.map((val, i) => {
return <Post key={i} title={val.title} author={val.by} />
});
return (
<div className="content-wrapper">
<h2>{this.props.currentSource}</h2>
{posts}
</div>
)
}
}
export default ContentWrapper;
Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result. Here is an example with a promise that resolves in 2 seconds.
Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .
You will have to use Promise.all
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
const topStories =
"https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
axios(topStories).then(res => {
const posts = [];
const requests = res.data.map(val => {
const url = `https://hacker-news.firebaseio.com/v0/item/${val}.json?print=pretty`;
return axios.get(url).then(res => {
posts.push(res.data);
});
});
// Wait for all requests, and then setState
return Promise.all(requests).then(() => {
this.setState({
posts
});
});
});
Test it here: https://runkit.com/embed/8pac53dhmy2y
Update There is also Promise.allSettled
which might be better in some cases if there are any errors in the promise array; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With