Search code examples
javascriptreactjsinfinite-scroll

React Infinite scrolling function by online API


I'm using YTS API and I would like to make Infinite scrolling function. There is a page parameter and limit parameter. It seems it can work with them but I have no idea of how to use it. I'm a beginner user of React. Could you help me?

fetch('https://yts.am/api/v2/list_movies.json?sort_by=download_count&limit=20')
fetch('https://yts.am/api/v2/list_movies.json?sort_by=download_count&page=2')

This is the link of YTS API https://yts.am/api#list_movies


Solution

  • I would try using React-Waypoint and dispatch an action to fetch the data every time it enters the screen.
    The best way IMO is using redux but here's an example without:

    state = { currentPage: 0, data: [] };
    
    getNextPage = () => {
      fetch(`https://yts.am/api/v2/list_movies.json?sort_by=download_count&page=${this.state.currentPage}`).
        then((res) => this.setState((prevState) => ({currentPage: prevState.currentPage + 1, data: res.body}));
    }
    
    render(){
      <div>
        {
          this.state.data.map((currentData) => <div>{currentData}</div>)
        }
        <Waypoint onEnter={this.getNextPage}/>
      </div>
    }