getting array from API and storing it into Movie state but when I try to map that movie I got the error:
"Property ‘map’ does not exist on type ‘never’."
import { useEffect, useState } from "react";
import MoviePoster from "../../Components/MoviePoster";
function Home() {
const [movie, setMovie] = useState();
const API_Url = `https://api.themoviedb.org/3/discover/movie?api_key=${process.env.REACT_APP_TMBD_KEY}`;
useEffect(() => {
getMovies();
}, []);
async function getMovies() {
const api = await fetch(API_Url);
const result = await api.json();
setMovie(result.results);
console.log(result.results);
}
return (
<div>
{movie?.map((data:any) => {
<MoviePoster key={data} {...data} />;
})}
</div>
);
}
export default Home;
the changes that I have applied… I just removed the common API part
import { useEffect, useState } from "react";
import MoviePoster from "../../Components/MoviePoster";
interface MovieList {
title: string,
id: string
}
function Home() {
const [movie, setMovie] = useState<MovieList[]>([]);
return (
<div>
{movie?.map((data:any) => {
<MoviePoster key={data.id} {...data.title} />;
})}
</div>
);
}
export default Home;
"consoled data image…."
2
Answers
In addtion to what has been said by Hatana in the comments, you could also add a loading screen. That way you can be sure that you have your data in your array before the component is rendered.
I think you need to return from the map
instead of
Created a codesandbox demo with this components. Have a look here