getImage is a sequence of promises required to return the url of an actor. sometimes it works sometimes it breaks, the error is:
Uncaught (in promise) TypeError: Cannot read property 'file_path' of undefined at getActorImage
code:
const getImage = async() => {
const page = getRandomInt(1,40);
const movielist = `https://api.themoviedb.org/3/movie/popular?&api_key=${key}&page=${page}`
const resp = await fetch(movielist);
const {results} = await resp.json();
const movieid = results[getRandomInt(0,results.length)].id
const castlist = `https://api.themoviedb.org/3/movie/${movieid}/credits?&api_key=${key}`
const resp2 = await fetch(castlist);
const {cast} = await resp2.json();
const id = cast[0].id;
const actor = `https://api.themoviedb.org/3/person/${id}/images?api_key=${key}`
const resp3 = await fetch(actor);
const {profiles} = await resp3.json();
const aux = profiles[0].file_path;
const url = `https://www.themoviedb.org/t/p/w600_and_h900_bestv2/${aux}`;
return (
url
)}
const useFetchActor = () => {
const [state, setstate] = useState({
path:'',
loading:true
})
useEffect( () =>{
getImage()
.then( image =>{
setstate({
path:image,
loading:false
})
})
},[])
return state;
}
Some cast don't have photo_path
, that's why it's showing undefined
. You can return a statement and end the function if cast doesn't have a photo_path
and show error message
// In getImage function
..
if (cast.length === 0 || !cast[0].profile_path) {
return "photo not found";
} else {
const id = cast[0].id;
const actor = `https://api.themoviedb.org/3/person/${id}/images?api_key=${key}`;
const resp3 = await fetch(actor);
const { profiles } = await resp3.json();
const aux = profiles[0].file_path;
const url = `https://www.themoviedb.org/t/p/w600_and_h900_bestv2/${aux}`;
return url;
}
};
// In useFetchActor function
..
useEffect(() => {
getImage().then((res) => {
console.log(res);
if (res === "photo not found") {
setImgNotFound(true);
return;
}
setstate({
path: res,
loading: false
});
});
}, []);
return imgNotFound ? (
<p>There is no image for this actor</p>
) : (
<img src={state.path} alt="actor" />
);