I have an application that gets movie information from an API as an array using the UseEffect hook and stores the response in state (movies), I also have a function (getIndexMovie) that gets a random movie object from the stored array of movies and stores the returned object in another state (selectedMovie). I would like to display a random movie information whenever the page loads, how can I achieve this?
I tried this:
const [movies, setMovies] = useState<TrendingMovieResultModel[]>([]);
const [selectedMovie, setSelectedMovie] = useState<SelectedMovieModel>({
"backdrop_path": "",
"title": "",
"original_language": "",
"original_title": "",
"poster_path": "",
"video": false,
"vote_average": 0,
"vote_count": 0,
"overview": "",
"release_date": "",
"id": 0
});
useEffect(() => {
fetch(`${baseUrl}trending/all/day?api_key=${API_KEY}`)
.then(response => response.json())
.then(data => {
setMovies(data.results);
}).catch(err => console.log(err));
}, []);
const getRand = (max: number) => {
return Math.floor(Math.random() * max);
}
//where can i call this function ?
const getIndexMovie = () => {
const randomIndex = getRand(movies.length);
const {
title, backdrop_path, original_language, original_title, poster_path,
video, vote_average, vote_count, overview, release_date,
id
} = movies[randomIndex];
setSelectedMovie({ backdrop_path, title, original_language, original_title,
poster_path, video, vote_average, vote_count, overview, release_date, id
});
}
You could do that by adding it to your useEffect
hook.
useEffect(() => {
fetch(`${baseUrl}trending/all/day?api_key=${API_KEY}`)
.then(response => response.json())
.then(data => {
setMovies(data.results);
const randIndex = getRand(data.results.length);
setSelectedMovie(data.results[randIndex]);
}).catch(err => console.log(err));
}, []);