I am pulling data from Themoviedb and right now you can only retrieve 20 results per page. I'm building a movie-rating application where the user can rate movies as they appear on the screen. One movie at a time is shown. When the user gets through the first 20 movies from Page 1, I want to automatically run a new request for Page 2 to get the next list of movies. I don't want the user to have to click a button to load more movies, or have a "Next Page" button or anything like that. Everything should be on the same page and load automatically.
Right now I am making the request in ComponentDidMount(), loading the list of movies into an array and storing that in my state, and I am clicking through the movies by keeping track of the array index. When I reach the end of the array, that's when I want to make another request for Page 2. This is where I'm having issues. My initial request is in ComponentDidMount(), so I'm not too sure how to handle a second request. Is there any way I can trigger this without a button click? I want something like when the array of the first 20 results is empty, request results from the next page. Would it be bad practice to call ComponentDidMount() again once array.length === 0?
My state:
state = {
currentMovieIndex: 0,
filteredMovieList: [],
currentPage: 1,
}
My request:
getAllMovies(page) {
return fetch(`https://api.themoviedb.org/3/discover/movie?api_key=2bb6427016a1701f4d730bde6d366c84&page=${page}`)
.then(res =>
(!res.ok)
? res.json().then(e => Promise.reject(e))
: res.json())
},
componentDidMount() {
Promise.all([
MovieService.getMyMovies(),
MovieService.getAllMovies(this.state.currentPage)
]).then(([arr1, arr2]) => {
// filter out movies that the user has already rated
let myMovieIds = [];
arr1.map(movie => {
myMovieIds.push(movie.id);
})
let filteredMovies = arr2.results.filter(val => !myMovieIds.includes(val.id))
this.setState({
filteredMovieList: filteredMovies,
});
})
}
If you want to implement a pagination logic without a "Next Page" button or another click trigger I think you should go and search about the "Cursor pagination" logic.
You should get the scroll event and calculate the position and call for more or next data when the scroll reaches a specific position.
(Sry, didn't found any good example!)