I have a class that does a lot of API Calls to populate the state so I'm doing it in the componentDidMount()
lifecycle hook like this:
async componentDidMount() {
await this.populateQuote();
await this.populateCustomers();
await this.populateEmployees();
await this.populatePropertyTypes();
}
and each of this functions are getting some data and setting some values in the state, now my problem is that every time one of the promises resolves it re-renders the page which I'd like to avoid, is there any way around this?
If you're using a React class component you can use the shouldComponentUpdate method or a React. PureComponent class extension to prevent a component from re-rendering.
You can see in the console tab, that the render lifecycle got triggered more than once on both the app and greeting component. This is because the React app component got re-rendered after the state values were modified, and it also re-rendered its child components.
React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.
Preventing Re-Renders: The Old Way To prevent the render method from being called, set the return to false, which cancels the render. This method gets called before the component gets rendered. Sometimes you may want to prevent re-render even if a component's state or prop has changed.
You should use Promise.all
to ensure that all Promises
in an array gets resolved before perform an operation
async componentDidMount(){
const calls = [call1(), call2(), call3()]
const results = await Promise.all(calls)
console.log(results[0],results[1],results[2])
}
Use Promise.all()
to fetch all data and then this.setState()
to perform the only re-render
async componentDidMount() {
const [quote, customers, employees, propertyTypes] = await Promise.all([
this.populateQuote(),
this.populateCustomers(),
this.populateEmployees(),
this.populatePropertyTypes()
]);
this.setState({
quote,
customers,
employees,
propertyTypes
});
}
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