I have an array that contains objects, inside an object. I can console.log the first object and the array, but when i try to access the objects within the array or use the map-function on the array i get an error that says "Can't read property of undefined".
I have thoroughly searched SO and other sites for similar problems and found some but no answers seems to work for me.
The object looks like this:
{ answers: [{…}], createdAt: "2019-01-23T10:50:06.513Z", nested: {kebab: "jjjj", sås: 2, sallad: "kkk"}, text: "weaxcc", /* etc... */ } And i can access it using: this.state.data
I want to access objects inside the answers-array like:
this.state.data.answers[0].text or even :
this.state.data.answers.map()..... But that gives me 'Cannot read property '0' of undefined. The answers-array is not empty.
Any help is appreciated!
EDIT This is how the objects ends up in my state.
getQuestionFromDb = () => { axios.get(`http://localhost:3000/questions/${this.state.id}`) .then(res => this.setState({ data: res.data })); }; This function is called in the ComponentDidMount()-method.
Here is my render function (the console.log is causing the error):
render() { return ( <div className="main-content"> <h2>{this.state.data.text} </h2> {console.log(this.state.data.answers[0].text)} <p>Introducing <strong>{this.state.id}</strong>, a teacher who loves teaching courses about <strong>{this.state.id}</strong>!</p> <input type="text" onChange={e => this.setState({ message: e.target.value })}> </input> <button onClick={() => {this.handleAnswerPost(this.state.message)}}>Answer</button> </div> ); } }