When I use this component, I get the following error. When I used the exact same function only with another API it worked and I got the output from the API.
TypeError: items.map is not a function ApiInfo.render C:/Users/32479/mikiesoftMovies2/cinemaReact-master/src/components/ApiInfo.js:35
32 | 33 | return ( 34 | <div className = "App"> 35 | <h1> Fetch data from an api in react </h1> { | ^ 36 | items.map((item) => ( 37 | <ol key = { item.id } > 38 | Title: { item.original_title }
When I try it with another API it worked and I got no errors at all. I'm new to React so I don't know what's wrong.
This is my code (with the API that gives me the error) it's just a code that requests the info from the API and puts it in an ol:
import React from "react";
export class ApiInfo extends React.Component {
// Constructor
constructor(props) {
super(props);
this.state = {
items: [],
DataisLoaded: false
};
}
// ComponentDidMount is used to
// execute the code
componentDidMount() {
fetch(
"https://api.themoviedb.org/3/movie/top_rated?api_key=55957fcf3ba81b137f8fc01ac5a31fb5&language=en-US&page=1")
.then((res) => res.json())
.then((res) => {
this.setState({
items: res,
DataisLoaded: true
});
})
}
render() {
const { DataisLoaded, items } = this.state;
if (!DataisLoaded) return <div>
<h1> Please wait some time.... </h1> </div> ;
return (
<div className = "App">
<h1> Fetch data from an api in react </h1> {
items.map((item) => (
<ol key = { item.id } >
Title: { item.original_title }
</ol>
))
}
</div>
);
}
}
export default ApiInfo;
and I will add an example of the json from the API I'm using: the json from the API unminified
The movies items that you are looking for, are returned by The Movie Database API in res.results, not in res:
this.setState({
items: res.results,
DataisLoaded: true
});
See the API Reference for top-rated movies
As a side note, it is a good practice to handle HTTP error cases, so consider adding a catch block to your fetch call.
The variable items is not an array. Therefore map is not a function. Print out the variable res and you will see what is hidden behind and what you have to assign to items.