Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React componentDidMount vs getInitialState

I have some questions about react usage and patterns.

Should I use

componentDidMount

or

getInitialState

in loading data asynchronously? What is the difference between the two?

I am using Backbone for my frontend data structures

this.props.data = new BrandModel({ _id: this.props.params.brandId });
var that = this;
this.props.data.fetch({
  success: function () {
    that.setState({ brand: that.props.brand });
  }
});
return null;

Update: thanks for the responses

This Question is suggesting to not us componentWillMount, but I understand that its more expressive to use componentDidMount in this case as getInitialState seems to be meant to be used synchronously

Update 2:

I've had to revert to using getInitialState as componentDidMount fires after render and I need this.props.data to be pointing to an object

like image 908
Dan Baker Avatar asked Jun 30 '15 19:06

Dan Baker


2 Answers

componentDidMount would be called after component was mounted into browser DOM (it would be called after first render and it would not be called if you are rendering server-side(to string)

getInitialState would be called when component is created, if you are using es6 class syntax you can place that logic in you component constructor directly assigning to this.state

There is also componentWillMount it would be called before first render for both server and client - it is more suitable in your case.

like image 124
Bogdan Savluk Avatar answered Nov 02 '22 15:11

Bogdan Savluk


Componentndid mount is fired after the render and we load the Ajax inside that.While during the actual render we check if the object has data, else send empty div

componentDidMount: function () {
            console.log("========> FIring");
            $.get("http://api.", function(response) {
                if (this.isMounted()) {
                    this.setState({
                    Data: response
                });
                }
            }.bind(this));
        },
        render: function() {
            var data = this.state.Data;
            if (this.state.promoData) {
             return (<div>{data}</div>
            );
            } else {
              return (<div className="divLoading">Loading...</div>);
            }
        }
like image 3
Rajat banerjee Avatar answered Nov 02 '22 15:11

Rajat banerjee