Nocktis
Nocktis

Reputation: 125

TypeError: Cannot read property 'length' of undefined, API TMDB

I am using the TMDB API which allows me to display movies in a list.

I have my Add.js component which allows me to make a query and search for the movies and add them to my list

But I get this error:

TypeError: Cannot read property 'length' of undefined

Add.js

import React, { useState } from "react";
import { ResultCard } from "./ResultCard";

export const Add = () => {
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);

  const onChange = (e) => {
    e.preventDefault();

    setQuery(e.target.value);

    fetch(
      `https://api.themoviedb.org/3/search/movie?api_key=${process.env.REACT_APP_TMDB_KEY}&language=en-US&page=1&include_adult=false&query=${e.target.value}`
    )
      .then((res) => res.json())
      .then((data) => {
        if (!data.errors) {
          setResults(data.results);
        } else {
          setResults([]);
        }
      });
  };

  return (
    <div className="add-page">
      <div className="container">
        <div className="add-content">
          <div className="input-wrapper">
            <input
              type="text"
              placeholder="Search for a movie"
              value={query}
              onChange={onChange}
            />
          </div>

          {results.length > 0 && (
            <ul className="results">
              {results.map((movie) => (
                <li key={movie.id}>
                  <ResultCard movie={movie} />
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
    </div>
  );
};

Upvotes: 0

Views: 333

Answers (2)

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8118

The problem is happening at this line of code:

.then((data) => {
    if (!data.errors) { // This is always giving error false since errors property is not returned from API
      setResults(data.results);
    } else {
      setResults([]);
    }
 });

The returned response data is:

{status_code: 7, status_message: "Invalid API key: You must be granted a valid key.", success: false} status_code: 7 status_message: "Invalid API key: You must be granted a valid key." success: false

The reason for this is because the data that is returned from the API has no errors property.

You need to use data.success property instead of data.errors.

THE CODESANDBOX WORKING CODE:

https://codesandbox.io/s/issue-1ng77?file=/src/App.js

Upvotes: 1

HichamELBSI
HichamELBSI

Reputation: 1719

For some reason, results is undefined.

Try to console log the result after fetching data, maybe you set your data to undefined or something.

To quickly fix that, you can do something like

{results?.length > 0 && ( ... )}

Upvotes: 0

Related Questions