I have a method called fetchMovies that I use to get data from an API as soon as the component mounts. What I'm trying to accomplish is to have a Load More movies button that calls the function again if clicked to get more movies, 20 movies at a time. However, I get an error saying that the method is undefined when it's used inside the LoadMoreMovies method. What could be a good way to get around this?
componentDidMount(){
const fetchMovies = async endpoint => {
const isLoadMore = endpoint.search('page');
try{
const result = await (await fetch(endpoint)).json();
this.setState(prev => ({
...prev,
movies: isLoadMore !== -1 ? [...prev.movies, ...result.results] : [...result.results],
heroImage: prev.heroImage || result.results[0],
currentPage: result.page,
totalPages: result.total_pages
}));
} catch(error){
alert(error);
}
}
console.log('...fetching');
fetchMovies(POPULAR_BASE_URL);
console.log('done fetching...');
}
loadMoreMovies = () => {
const searchEndpoint = `${SEARCH_BASE_URL}${this.state.searchTerm}&page=${this.state.currentPage + 1}`;
const popularEndpoint = `${POPULAR_BASE_URL}&page=${this.state.currentPage + 1}`;
const endpoint = this.state.searchTerm ? searchEndpoint : popularEndpoint;
fetchMovies(endpoint);
}
render(){
const {heroImage, movies, searchTerm, currentPage, totalPages, loading} = this.state;
console.log('rendered');
return(
<React.Fragment>
{currentPage < totalPages && !loading && (
<LoadMoreBtn text="Load More" callback={this.loadMoreMovies}/>
)}
<React.Fragment/>