Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Component Renders too early

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?

like image 810
Moses Schwartz Avatar asked Aug 26 '19 13:08

Moses Schwartz


People also ask

How do you prevent components from Rerendering?

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.

Why does component render multiple times?

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.

What causes a component to get re-rendered?

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.

How do I stop component from rendering on state change?

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.


2 Answers

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])
}
like image 145
Dupocas Avatar answered Jan 03 '23 16:01

Dupocas


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
  });
}
like image 40
Dmitriy Chuvichkin Avatar answered Jan 03 '23 16:01

Dmitriy Chuvichkin