Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ajax request should be done in componentDidMount in React components?

Tags:

reactjs

React documentation states that ajax request should be initiated from componentDidMount lifecycle event (see react docs) .

Why this event?

In most cases, when loading data using ajax, I want to display some kind of loading bar, e.g.:

componentDidMount() {
   this.setState({isLoading: true});
   fetch(...)
      .then(...)
      .then(() => this.setState({isLoading: false})  
}

but this fires render method 3 times (initial render immediatelly followed by setting isLoading = true and then by isLoading = false

What's wrong about sending ajax request from componentWillMount event?

like image 395
Liero Avatar asked Jul 04 '16 09:07

Liero


1 Answers

Well, isLoading: true could be part of the initial state, no need to set it after component did mount => only 2 renderings, not 3.

According to https://github.com/reactjs/react-redux/issues/210, the consequence of calling render only once from componentWillMount means that if setState will be asynchronously called after render, it won't have any effect (if I understand the comments correctly).

Not sure if there is a chance that the callback with setState can execute before render and thus no loading screen will be visible, only the results, thus sometimes it would "work" (most likely in DEV) but in reality it would be a race condition very hard to debug...

See also: https://reactjs.org/docs/faq-ajax.html

like image 157
Aprillion Avatar answered Nov 13 '22 06:11

Aprillion