Siki Damjanovic
Siki Damjanovic

Reputation: 13

How can I access API object properties in React?

I'm having trouble accessing an object using React. The object was generated using tMDB API. Once I can access the object, I would like to pass the ID prop down to a child component.

Home:

import React, {Component} from 'react'
import Movie from '../components/Movie'
import '../index.css'

class Home extends Component{

  constructor(props) {
    super(props)
    this.state = {
      movie: [],
    }
  }

  componentDidMount() {
    this.fetchData()
  }

  fetchData(){
    fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=17c21a1abd8ae7be6ee8986389011906')
      .then(response=> response.json())
      .then( ({results: movie}) => this.setState({movie}))
  }

  render() {

    console.log(this.state.movie[1].id);

    return(
        <div className="main">
          <div>

         </div>
        </div>
    )
  }
}

export default Home

This outputs TypeError: Cannot read property 'id' of undefined

If I change this.state.movie[1].id to this.state.movie[1] I can see the full object and it's properties, but cannot access child properties in the code.

I believe the problem might be that React is rendering the state twice since there is an 'undefined' object right above the movie object. If so, how could I fix that?

Console:

Array(0)
length
:
0
__proto__
:
Array(0)
Home.js:26 

Array(20)
0:
{vote_count: 4600, id: 284053, video: false, vote_average: 7.4, title: "Thor: Ragnarok", …}
1:
{vote_count: 2314, id: 284054, video: false, vote_average: 7.4, title: "Black Panther", …}
2:
{vote_count: 771, id: 337167, video: false, vote_average: 6.3, title: "Fifty Shades Freed", …}
...

Upvotes: 0

Views: 370

Answers (1)

AngelSalazar
AngelSalazar

Reputation: 3113

You have to validate if movie is empty, as your api call takes some time to get a response. Keep in mind that react rerenders you component every time you modify your state using setState

render() {
    if (this.state.movie.length === 0) {
     return (<div>Loading data...</div>)
    }

    console.log(this.state.movie[1].id);

    return(
        <div className="main">
          <div>

         </div>
        </div>
    )
  }

Upvotes: 1

Related Questions