Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put ajax in React component constructor?

import React from 'react';

class AjaxInConstructor extends React.Component {
  constructor() {
    super();
    this.state = { name: '', age: '' };
    this.loadData().then((data) => {
      this.setState(data);
    });
  }
  // simulate the AJAX (network I/O)
  public loadData() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve({
          name: 'slideshowp2',
          age: 123,
        });
      }, 2000);
    });
  }

  public render() {
    const { name, age } = this.state;
    return (
      <div>
        <p>Can I init component state async?</p>
        <p>name: {name}</p>
        <p>age: {age}</p>
      </div>
    );
  }
}

ReactDOM.render(<AjaxInConstructor />, document.body);

Above is my demo code. I know people always put ajax in componentDidMount or componentWillMount lifecycle.

But this case also works.

In chrome console, React throw no error and waring. So, My Question is usage like this is completely correct ? Is there have some error?

like image 374
slideshowp2 Avatar asked Aug 12 '16 08:08

slideshowp2


People also ask

Can AJAX be used with React?

You can use any AJAX library you like with React. Some popular ones are Axios, jQuery AJAX, and the browser built-in window. fetch.

Does React component need constructor?

If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component. The constructor for a React component is called before it is mounted.


1 Answers

You can make an AJAX call wherever you want. There is nothing "wrong" in making an AJAX call in the constructor, but there is a catch. You'll want to make the AJAX call only after the component has been mounted or just before it is about to be mounted.

So before component is rendered, making an AJAX call in componentDidMount() or componentWillMount() is recommended. Just because React allows to do "things" does not mean you should! :)

UPDATE

I also realize that initially my answer wasn't rigorous. I have always followed what fellow programmer have followed, blindly.

After searching a bit I found these to be one step closer to the complete answer- Why ajax request should be done in componentDidMount in React components?

Essence of those answer says that when you call setState() in componentWillMount(), the component will not re-render. Therefore one must use componentDidMount(). After further reading I learned that it was fixed in subsequent release by React team. You can now call setState() in componentWillMount(). I think that is the reason why everyone recommends making AJAX calls in didMount.

One of the comments also puts forth my thoughts very articulately-

well, you are not calling setState from componentWillMount nor componentDidMount directly, but from a new async stack. I have no idea how exactly react is implemented to keep reference to this with live event listeners from various methods. if using undocumented features is not scary enough for you and want a bit of excitement that it might work and maybe even in future versions, then feel free, I don't know whether it will break or not

like image 185
Mihir Avatar answered Sep 30 '22 07:09

Mihir