Rachel Lanman
Rachel Lanman

Reputation: 509

accessing state data in componentDidMount

Why is it not possible to access this.state.board within componentDidMount? As I understand it, once the component has been rendered, componentDidMount is fired immediately after, and only once.

I am trying to set up a Google Analytics ecommerce tracker, and so I thought the best place to set that up would be within the componentDidMount because it ensures that the GA tracker is called only once. However, I am not able to access any of the state data to send back to GA. Any ideas?

    //function which establishes state
    function getEditorState() {
        var board = Editor.getCsb();
        var similarBoard = Editor.getSimilarLsbs();
        return {
            board: board,
            similarBoard: similarBoard,
            editing: Editor.isEditing(),
            hoverColor: Editor.getHoverColor(),
            variant: Editor.variant(),
            lidAndLsb: Editor.getLidAndLsb()
        };
    }



  //component    
    var CsbEditorApp = React.createClass({

            getInitialState: function () {
                return getEditorState();
            },

            componentDidMount: function () {
              console.log(this.state.board); // <---- this returns an empty object.
              Editor.addChangeListener(this._onChange);
              SbAction.loadCsb(this.props.params.cid);
           }, 

           render: function() {
             console.log(this.state.board); // <---- this returns the the board object with data. 
           return (
            <div className={cm('lightbox sb-bg overlay-border')} ref="app">
                <Header board={this.state.board} label={this.state.label} socialLinkStatus={this.state.socialLinkStatus} buyingAll={this.state.buyingAll} />
                <div className="viewer-content">
                    <div id="csb-content">
                        <MetaText className="meta-author" metaKey="author" board={this.state.board} />
                        <BoardMeta board={this.state.board}/>
                        <CsbPanel board={this.state.board hoverColor={this.state.hoverColor} showPanel={showPanel} />

                        <RouteHandler/>
                    </div>
                </div>
            </div>
        );
    }, 
 _onChange: function () {
        this.setState(getEditorState());
        $("#cc_hover").hide();
    }
}); 

Upvotes: 0

Views: 983

Answers (1)

Igorsvee
Igorsvee

Reputation: 4201

console.log is not a reliable method of debugging - the method is async and actually can get called after you've set up your listener or even after the callback it registers (which affects the state) has been triggered, so use the debugger. Also, try commenting out the Editor.addChangeListener(this._onChange); line and see if it causes the problem.

Upvotes: 0

Related Questions