I am trying to make a movie search app with React and have made an API call to The Movie Database API. I have this form and what I am trying to do is get the data of the movie that I am searching for.
I am not able to access the data from the API call, and I get this error of “Uncaught TypeError: Cannot read property ‘map’ of undefined”
I have two js files: 1 index.js
JavaScript
x
19
19
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
import SearchMovies from "./searchMovies";
4
import './style.css';
5
6
class Main extends React.Component {
7
render() {
8
return (
9
<div className="container">
10
<h1 className="title">React Movie Search</h1>
11
<SearchMovies/>
12
</div>
13
14
);
15
}
16
}
17
18
ReactDOM.render(<Main />, document.getElementById('root'));
19
The second file is searchMovies.js
JavaScript
1
53
53
1
import React, {useState} from "react";
2
3
export default function SearchMovies(){
4
5
//states- input query, movies
6
const [query, setQuery] = useState('');
7
const [movies, setMovies] = useState([]);
8
9
const searchMovies = async (e) => {
10
e.preventDefault();
11
12
const url = `https://api.themoviedb.org/3/movie/550?
13
api_key=api_key&language=en-US&query=${query}&page=1&
14
include_adult=false`;
15
16
try {
17
const res = await fetch(url);
18
const data = await res.json();
19
setMovies(data.results);
20
}catch(err){
21
console.error(err);
22
}
23
}
24
25
26
return(
27
<div>
28
<form className="form" onSubmit={searchMovies}>
29
<label htmlFor="query" className="Label">Movie Name</label>
30
31
<input className="input" type="text" name="query" placeholder="i.e. Jurassic
32
Park"
33
value={query} onChange={(e) => setQuery(e.target.value)}
34
/>
35
36
<button className="button" type="submit">Search</button>
37
</form>
38
<div className="card-list">
39
{movies.map(movie => (
40
<div className="card">
41
<img className="card--image"
42
src={`https://image.tmdb.org/t/p/w185_and_h278_bestv2/
43
${movie.poster_path}`}
44
alt={movie.title + ' poster'}
45
/>
46
47
</div>
48
))}
49
</div>
50
</div>
51
)
52
}
53
Can somebody tell me what I am doing wrong here? I am new to React. Many thanks!