everyone, and thank you in advance to this great community.
I have created a Web app with ReactJS that gets a JSON from a API, in this case a movie database with all the details of a particular movie, up to this point everything is working fine.
When the web app tries to read data that a particular movies does not have, in this case, not all movies have rotten tomatoes rating, it crashes, i destructured the object to give it a default value, but it still crashes if does not find the value, can anyone point me in the right direction ?
export default function MovieDetail(props) {
const imdbId = props.location.detailsProps;
const [favorited, setFavorited] = useState(false);
const [details, setDetails] = useState({
Runtime: '',
Year: '',
Rated: '',
Title: '',
Ratings: [{
Source: '',
Value: '',
},
{
Source: '',
Value: '',
},
],
Plot: '',
Actors: '',
Genre: '',
Director: '',
});
useEffect( ()=>{
apiCall();
}, [] );
const showFavorite = (e) => {
setFavorited(true);
};
const apiCall = async () => {
const url = 'http://www.omdbapi.com/?i='+imdbId.id+'&apikey=536a34c3';
console.log(imdbId.id);
const response = await axios.get(url)
.then((response) => setDetails(response.data));
};
if (!details) return null;
return (
<div className="body">
<div className="logo">
<img src={logo} alt="logo" />
</div>
<Link to="/" className="Link">
<img src={arrow} alt="arrow" />
</Link>
<div className="runtime">
<h1>{details.Runtime}</h1>
<p>.</p>
<h1>{details.Year}</h1>
<p>.</p>
<h2>{details.Rated}</h2>
</div>
<div className="title">
<h1>{details.Title}</h1>
</div>
<div className="rottenImdb">
<img src={imdbLogo} alt="imdbLogo" />
<h2>{details.Ratings[0].Value}</h2>
<img src={rottenLogo} alt="rottenLogo" className="rotten"/>
<h2>{details.Ratings[1].Value}</h2>
</div>
<div className="favorite" onClick={showFavorite}
style={{visibility: favorited ? 'hidden' : ' '}}>
<img src={favoriteHeart} alt="heart"/>
<h2>Add to favourites</h2>
</div>
<div className="favorited" onClick={showFavorite}
style={{visibility: favorited ? 'visible ' : 'hidden'}}>
<img src={favoritedHeart} alt="heart"/>
<h2>Added</h2>
</div>
<div className="plot">
<h1>Plot</h1>
<h2>{details.Plot}</h2>
</div>
<div className="technical">
<div className="cast">
<h1>Cast</h1>
<h2>{details.Actors}</h2>
</div>
<div className="genre">
<h1>Genre</h1>
<h2>{details.Genre}</h2>
</div>
<div className="director">
<h1>Director</h1>
<h2>{details.Director}</h2>
</div>
</div>
<div className="poster">
<img src={details.Poster} alt="poster" />
</div>
</div>
);
}
