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?
Assuming your component is rendered regardless of if Axios has returned yet, the
personData
prop will benull
(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 ofpersonData
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.