Axios response not available in nested React component

496 Views Asked by At

Thanks for reading. I know this is going to seem over-simplified, but I am really stumped as to why this behavior is happening. I am calling an API using axios, getting the answer back, and passing that answer to the component below via props. When I let the following code execute, the console shows the object - populated with the server/api data.

class Player extends React.Component{
    constructor(props) {
        super(props);
    }   

    render() {
        console.log(this.props.personData)
        return ...
    }
}

If I add a field: console.log(this.props.personData.first_name) I get an error that personData is null, can't access its members. Thought that was weird, so stepped back to test and stumped myself further:

If I set a breakpoint in Chrome at the console.log line and instead type this.props.personData into console I get null. If I then step over the console.log line, it outputs null. But if I remove the breakpoint, that same line of code outputs a data-populated object.

Can anyone explain this behavior?

2

There are 2 best solutions below

1
On BEST ANSWER

Assuming your component is rendered regardless of if Axios has returned yet, the personData prop will be null (or whatever you construct it in the parent's state) until Axios returns the async call.

You can either conditionally render the Player component once the data returns, or don't reference attributes of the data until you know it's not null.

This is because the Player component will be rendered initially when the parent mounts, however, the Axios API call will be async so the data isn't available.

Also, if the Player component is rendering attributes of personData without checking that they exist, it will throw and error and break the rendering cycle.

As to your question about breakpoint / logging differences, it's because the console log is mapped to the memory location of the prop, so eventually it is set and will display in the log. But, if you check by a breakpoint when you initially render it, the value will be null, and it will throw the above mentioned error.

0
On

HOw you are passing data to the component using redux or flux.