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
JavaScript
x
53
53
1
import React, { useState } from "react";
2
import { ResultCard } from "./ResultCard";
3
4
export const Add = () => {
5
const [query, setQuery] = useState("");
6
const [results, setResults] = useState([]);
7
8
const onChange = (e) => {
9
e.preventDefault();
10
11
setQuery(e.target.value);
12
13
fetch(
14
`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}`
15
)
16
.then((res) => res.json())
17
.then((data) => {
18
if (!data.errors) {
19
setResults(data.results);
20
} else {
21
setResults([]);
22
}
23
});
24
};
25
26
return (
27
<div className="add-page">
28
<div className="container">
29
<div className="add-content">
30
<div className="input-wrapper">
31
<input
32
type="text"
33
placeholder="Search for a movie"
34
value={query}
35
onChange={onChange}
36
/>
37
</div>
38
39
{results.length > 0 && (
40
<ul className="results">
41
{results.map((movie) => (
42
<li key={movie.id}>
43
<ResultCard movie={movie} />
44
</li>
45
))}
46
</ul>
47
)}
48
</div>
49
</div>
50
</div>
51
);
52
};
53
Advertisement
Answer
The problem is happening at this line of code:
JavaScript
1
8
1
.then((data) => {
2
if (!data.errors) { // This is always giving error false since errors property is not returned from API
3
setResults(data.results);
4
} else {
5
setResults([]);
6
}
7
});
8
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: