Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching data in constructor

Is a good practice to fetch data in javascript class constructor()?

E.g. In react class constructor(), every tutorial which I find fetch data in componendDidMount(), but no one explein why We can't do it in constructor().

Question concerns javascript classes at all, not only react.

like image 974
Michaell94 Avatar asked Mar 15 '19 12:03

Michaell94


2 Answers

Constructor is called before the component is mounted (as stated here in #constructor doc: https://reactjs.org/docs/react-component.html).

To answer your question, the explanation lies in the lifecycle of a react component and the need to redraw when the state changes. By doing async calls in constructor, you may trigger setState before your component is mounted.

Doing async calls in constructor will mess with the re-render and your component will sometimes not re-render if you call setState in the constructor.

From doc:

You should not call setState() in the constructor(). Instead, if your component needs to use local state, assign the initial state to this.state directly in the constructor:

Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use componentDidMount() instead.

like image 127
Quentin C Avatar answered Nov 11 '22 23:11

Quentin C


A class constructor is a function which gets called only when function initialises for the first time in DOM. In trivial language behaviour, only when we instantiate a class using new keyword, its constructor gets called. Now if we fetch data in Javascript Classes constructor:

  1. In case as React if the data fetched is responsible for interacting with DOM(UI), it will fail as DOM gets ready only after component mounts, assured by componentDidMount.

  2. The Data fetching function will also not be called when component re renders as constructor is called only once and hence data wont update for UI(DOM)

Constructors are used generally for default value assignment and declaring class related attributes.

like image 35
adroit18 Avatar answered Nov 12 '22 00:11

adroit18