React - Can't access a property of an object stored in state?


I’m wondering if someone can explain to me why the following code does not work.

class App extends React.Component {
  constructor() {
    this.state = {
      data: []
  componentDidMount() {
    fetch('').then(response => {
      response.json().then(data => {
          data: data.Search
  render() {

  <App />,

When I console.log([0]) it returns the object with a property of Title. But when I console.log([0].Title) it returns undefined.

How can I map over the object the way that I would with a typical array?


The problem is that console.log([0]); gets called two times:

  1. When the page first loads, before you have a chance to load data from the API.
  2. After the API request finishes and you call this.setState

I would check that data's length is greater than 0 before trying to use it. Try changing console.log([0]); to this:

if ( > 0) {

Does that work how you want it to?


Yes, that did work. Thank you! I don’t understand why this works though?

Also, now that I can access, how can I map over it to display the title of every object?


When React renders for the first time data is an empty array, meaning[0] doesn’t exist yet because you haven’t sent and received your API request yet. JavaScript doesn’t mind trying to read an array element that doesn’t exist, but it doesn’t want you to try to access a property (that doesn’t exist) on an element that doesn’t exist, so it throws an error.

Since you hit an error the first time React renders, the code just stops and render doesn’t get called a second time (which is when[0] will exist and you can use it).

If you run your original code you’ll see that two things get logged to the console (one for each render React does: undefined and the object you’re expecting.

The if prevents accessing the Title property if the array has no elements, so it avoids the error.

As for mapping the array, I would do something like

render() {
  let movieTitles;
  if ( {
    movieTitles =
      (obj) => (<h2>{obj.Title}</h2>)
  } else {
    movieTitles = <h1>Working</h1>;

  return <div>{movieTitles}</div>;

This makes an array of h2 elements with movie titles, if is loaded, or the original header if not.

Let me know if that code is confusing or anything. Try improving on it and see what you can do with it


Thank you very much for the detailed response. That makes a lot of sense to me now.