0

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/>
albert_anthony6
  • 594
  • 2
  • 9
  • 30
  • https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – imjared Feb 18 '20 at 17:51
  • Yes, you define `fetchMovies` in the scope of `componentDidMount`. Of course it isn't available in `loadMoreMovies` unless you expose it to some broader scope. – zero298 Feb 18 '20 at 17:51

1 Answers1

1

You defined your 'fetchMovies' function inside the 'componentDidMount', so outside from that scope the function would be surely undefined. you need to define the fetchMovies inside the component but outside the componentDidMount for it to work

Tom Mendelson
  • 625
  • 4
  • 10