Home > other >  themoviedb api Search Movie
themoviedb api Search Movie

Time:03-05

I'm stuck. I am using movie api for search movie. I have done the api part. But when I type a random nonsense word in the search section, my application gives an error because there is no such movie. How can I get past this? I am sharing my codes below.

Thats movie area;

 <div>
      <h4>{movie[0].title}</h4>
      <img
        src={`${base_URL}${movie[0].poster_path}`}
        alt={movie[0].title}
      />
    </div>

Thats search from

<label>
      <span>Search Film:</span>
      <input
        type="text"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
      />
    </label>

Thats States

 const [movie, setMovie] = useState([{ title: "The Matrix Resurrections" }]); 

 const [search, setSearch] = useState("The Matrix Resurrections");

movie1

movie2

myError when i type "sadsafasfas" search bar

CodePudding user response:

That is because the response you got from searching "nonsense" value using themoviedb api returning an empty object. To get through this, you can use a conditional component that checks the value of movie[0]. Your code can be written like this

<div>
{
   movie[0] ?
     <>
      <h4>{movie[0].title}</h4>
      <img
        src={`${base_URL}${movie[0].poster_path}`}
        alt={movie[0].title}
      /> 
     </>
       :
     <>
      <h4>Sorry, movie not found</h4> //your component if nothing returned from api
     </>
 }   
</div>

  • Related