Search code examples
javascriptreactjsthemoviedb-api

TMbd Movie DB - Upcoming Movies - "Cannot read properties of undefined" after refreshing page


I am getting the error when trying to fetch upcoming movies from the tmbd API:

"Cannot read properties of undefined (reading 'poster_path') error"

Here is my component:

import React from "react";
import { useState, useEffect } from "react";


const HeroSection = () =>{
  
  const [upcomingMovies, setUpcomingMovies] = useState([]);
    const getUpcomingMoviestoFeature = () => {
      const options = {method: 'GET', headers: {
        accept: 'application/json',
        Authorization: 'Bearer authorizationkeynumber'
      }};

fetch(`https://api.themoviedb.org/3/movie/upcoming?language=en-US&page=1?api_key=${process.env.REACT_APP_MOVIE_KEY}`, options)
  .then(response => response.json())
  .then(response => 
    // console.log(response.results[0].original_title)
    setUpcomingMovies(response.results)
   
    
    )
    
  .catch(err => console.error(err));
  
    }
    useEffect(() => {
      getUpcomingMoviestoFeature();
  }, []);

    
      {
      if(!upcomingMovies) {
        return (
          <p>Loading</p>
        )
      } else {return (
        <>
      <div className="heroSection">
      <section className="light hero">
        <div className="heroInner">
      
               
                
                
                <img src = {`https://image.tmdb.org/t/p/w500/${upcomingMovies[0].poster_path}`} />
                
        
      
         
         
        
      
        </div>
      </section>
    </div></>
  
    )}
          
       
      }
     
   
    
  };
  
  export default HeroSection;
  

I tried to add conditional rendering to make sure it would not load the component until the data is available but that did not work.


Solution

  • When component is first rendered, upcomingMovies = [], !upcomingMovies = false, upcomingMovies[0] = undefined, but trying to get upcomingMovies[0].poster_path. This is the problem.

    Please update the condition like this.

    if (!upcomingMovies || !upcomingMovies.length) {
        return (
            <p>Loading</p>
        )
    }