I'm working on a react.js project and I need to access an array of objects. I get the objects from an external URL and there's no issue there. Inside my component's render method I can see the array:
const array = this.state.data.myArray;
console.log({array});
Now I try to look at the first object:
console.log({array}[0]);
but it's undefined.
I tried various combinations with or without the curly brackets but it's always undefined, or gives an unexpected token error.
How do I get to the array's objects?
EDIT:
Looks like my render method is called twice. The first time it's with the array undefined and the second time it has data, but by now it's no longer rendering.
Here's my component:
import React from 'react'
class Hello extends React.Component {
constructor() {
super();
this.state = { data: [] };
}
async componentDidMount() {
const url = 'http://localhost:9000/SomeJson/id';
const response = await fetch(url);
const data = await response.json();
this.setState({ data });
console.log(data); // data shows up in the console
}
render() {
alert(this.state.data.theArray);
return(
<div><h2>hello</h2></div>
);
}
}
export default Hello;
What am I missing here?
array[0]ifarrayis a valid Array. can you show output forconsole.log(array);arraywith value of your array.console.log(array[0])is probably fine, if it isn't, you should show the output forconsole.log(array);as stated aboverendermethod is called twice. I edited the question with more information.