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
import React from 'react';
import ReactDOM from 'react-dom';
import SearchMovies from "./searchMovies";
import './style.css';
class Main extends React.Component {
render() {
return (
<div className="container">
<h1 className="title">React Movie Search</h1>
<SearchMovies/>
</div>
);
}
}
ReactDOM.render(<Main />, document.getElementById('root'));
The second file is searchMovies.js
import React, {useState} from "react";
export default function SearchMovies(){
//states- input query, movies
const [query, setQuery] = useState('');
const [movies, setMovies] = useState([]);
const searchMovies = async (e) => {
e.preventDefault();
const url = `https://api.themoviedb.org/3/movie/550?
api_key=api_key&language=en-US&query=${query}&page=1&
include_adult=false`;
try {
const res = await fetch(url);
const data = await res.json();
setMovies(data.results);
}catch(err){
console.error(err);
}
}
return(
<div>
<form className="form" onSubmit={searchMovies}>
<label htmlFor="query" className="Label">Movie Name</label>
<input className="input" type="text" name="query" placeholder="i.e. Jurassic
Park"
value={query} onChange={(e) => setQuery(e.target.value)}
/>
<button className="button" type="submit">Search</button>
</form>
<div className="card-list">
{movies.map(movie => (
<div className="card">
<img className="card--image"
src={`https://image.tmdb.org/t/p/w185_and_h278_bestv2/
${movie.poster_path}`}
alt={movie.title + ' poster'}
/>
</div>
))}
</div>
</div>
)
}
Can somebody tell me what I am doing wrong here? I am new to React. Many thanks!