monkeyjumps
monkeyjumps

Reputation: 712

Uncaught TypeError: Cannot read property 'ImageRoute' of undefined

I have a simple set of components that all are composed of the following main component. The document component exposes its event handler from its props property. The event fires all the way up as expected. However once its caught in the main component, i try to set the state. Upon setting the state inside the event handler it throws an error the first time i try and retrieve the state. Every subsequent attempt works as expected.

In the example image below it shows the first time i set and try to print out the value of ImageRoute from the document object it fails then works every single time after.

selectedDocument is the eventhandler

Anybody have an explanation?

var Workstation = React.createClass({
getInitialState: function () {
    return {};

},
selectedDocument :function(obj, clickedNumber){
    var component = this;
    console.log(obj.ImageRoute)
    console.log(clickedNumber + " was clicked")
    component.setState({ selectedDocument: obj });

    console.log("selectedDocument set")

    if (this.isMounted()) {
        console.log(this.state.selectedDocument.ImageRoute)
    } else {

        console.log("not mounted")
    }
},

render: function () {

    return (

        <div>
            <DocumentQueue initialData={jsonData.initialData} selectedDocument={this.selectedDocument} />
            <ImageViewer src={this.state.selectedDocument==null ? this.state.selectedDocument : this.state.selectedDocument.ImageRoute} />
        </div>
        );
}

});

enter image description here

Upvotes: 0

Views: 394

Answers (1)

John Ruddell
John Ruddell

Reputation: 25862

you havent set the state yet. what I mean is the setState function is async and doesn't wait until the state is set before moving to the next line of code. you can use a callback function to set this up correctly

var component = this;
console.log(obj.ImageRoute)
console.log(clickedNumber + " was clicked")
component.setState({ selectedDocument: obj }, function(){
    console.log("selectedDocument set")

    if (component.isMounted()) {
        console.log(component.state.selectedDocument.ImageRoute)
    } else {
        console.log("not mounted")
    }
});

Upvotes: 1

Related Questions