Reputation: 310
I have a object saved in state here is what is looks like when console.logged.
[{…}]
0:
NameOfUser: "James"
QuestionStatus: "Complete "
Date: (2) ["2020-03-10T14:13:45.257Z", "2020-03-10T14:13:45.257Z"]
AssignedWorkstation: "hello"
Email: "[email protected]"
ContactNumber: "12345678987654321"
__proto__: Object
length: 1
__proto__: Array(0)
to console log this I have just done this
console.log(this.state.WSAHeader);
How would I access the individual properties of this object.
I have tried
console.log(this.state.WSAHeader.NameOfUser);
This says it is undefined. How would I just access for example the NameOfUser property from this object stored in state.
I have also tried
console.log(this.state.WSAHeader[0].NameOfUser);
I am just looking for a suggestion for what is going wrong.
whole class
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
answeredQuestions: [],
WSAHeader: []
};
this.getWSAAnsweredQuestions = this.getWSAAnsweredQuestions.bind(this);
this.getWSAHeader = this.getWSAHeader.bind(this);
}
getWSAAnsweredQuestions() {
let data = {
WSAId: this.props.location.state.WSAId
};
fetch("/get-completed-questions", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(recordset => recordset.json())
.then(results => {
this.setState({ answeredQuestions: results.recordset });
console.log(this.state.answeredQuestions);
});
}
getWSAHeader() {
let data = {
WSAId: this.props.location.state.WSAId
};
fetch("/get-WSA-header", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(recordset => recordset.json())
.then(results => {
this.setState({ WSAHeader: results.recordset });
console.log(this.state.WSAHeader);
});
}
componentDidMount() {
this.getWSAHeader();
this.getWSAAnsweredQuestions();
}
render() {
// alert(this.state.WSAHeader.NameOfUser);
console.log(this.state.WSAHeader);
console.log(this.state.WSAHeader[0].NameOfUser);
console.log(this.state.WSAHeader.QuestionStatus);
return (
<>
<Header />
{/* <h3 style={{ textAlign: "center" }}>Workstation Assessment</h3> */}
<DisplayWSAHeader WSAHeader={this.state.WSAHeader} />
<WSAAnsweredQuestions
WSAHeader={this.state.WSAHeader.AssignedWorkstation}
answeredQuestions={this.state.answeredQuestions}
amountOfQuestions={this.state.answeredQuestions.length}
/>
</>
);
}
}
Upvotes: 4
Views: 84
Reputation: 527
Answer from the question's comments
It's not defined at the time of console.log
. This is true if before you expand the array in the console, it says length: 0
but then when you expand it, it says length: 1
.
This is because you're loading the data after the component mounts so it will be empty the first time around. If you check that the array has been populated first before accessing it, it will work.
Upvotes: 1