import React, { Component } from 'react';
import axios from 'axios';
class Home extends Component {
state = {
responses: []
}
componentDidMount() {
this.fetchQuestionAnswers();
}
fetchQuestionAnswers = () => {
if (this.state.activeSupervisionId) {
axios.get('/question/response/' + this.state.activeSupervisionId).then(res => {
this.setState({ responses: res.data.data || [] });
console.log(this.state.responses[0].value)
// dot notation work here inside the function
}).catch(err => console.error(err));
}
}
render() {
console.log(this.state.responses[0].value)
// dot notation not working here under render function but the result of // console.log(this.state.responses[0]) is printed
return (
)
}
}
export default Home;
I fetch a data from an API that was sent as array of objects. So lets say I set the state of responses: res.data.data
. The result of responses console appear as described below.
var responses = [0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…},...]
Index Value
I will use the 0 index object as an example of what I am trying to achieve. I have searched other answers but couldn't figure it out.
0: {
id: 5,
questionId: 1,
score: "0",
text: "Are there any others",
value: {
designations: {
CCO: { no: "3" },
CDD: { no: "1" },
DSNO: { no: "1" }
},
reaportedStaff: [ "DSNO", "CCO", "CDD" ]
staffLivingInQuarter: "yes"
totalReaportedStaff: 5
}
}
I want to know how I can access the value of properties inside the objects in the array with dot notation or other method i.e id, score, text, CCO no?
Please note that I have tried responses[0].value
and it printed TypeError: Cannot read properties of undefined (reading 'value')