fetchMovies function
Sat Feb 08 2025 00:31:07 GMT+0000 (Coordinated Universal Time)
Saved by
@fastoch
#javascript
const fetchMovies = async () => {
// set the loading state to true so the loading indicator is displayed as soon as the function is called
setIsLoading(true);
try {
// endpoint for fetching movies and sorting them by popularity (descending)
const endpoint = `${API_BASE_URL}/discover/movie?sort_by=popularity.desc`;
// calling the endpoint with the API options
const response = await fetch(endpoint, API_OPTIONS);
// parsing the response into a json object
if (!response.ok) {
throw new Error('Failed to fetch movies');
}
const data = await response.json(); // if successful response, parse the data
console.log(data); // just to see what we get from the API (over 48000 pages and almost a million movies)
// if we get no response, set the error message, and set the movies state to an empty array
if(data.Response === 'False') {
setErrorMessage(data.Error || 'Failed to fetch movies');
setMovies([]);
return; // exit out of the function
}
// if we get a response, set the movies state with the fetched data
setMovies(data.results || []);
/*
The empty array in `setMovies(data.results || [])` ensures that the `movies` state is always set to a valid array,
even if the API response does not include the expected `results` property or if it is `null` or `undefined`.
*/
} catch (error) {
console.error(`Error while fetching movies: ${error}`);
setErrorMessage('An error occurred while fetching movies. Please try again later.');
} finally {
// set the loading state to false after the fetch is complete (whether successful or not)
setIsLoading(false);
}
}
content_copyCOPY
this function fetches movies from the TMDB API
it's part of the App component in a React movie App built via a JS Mastery tutorial (URL below)
https://www.youtube.com/watch?v=dCLhUialKPQ&t=1478s
Comments