Monday, 5 August 2019

Creating a todos list using react-infinite-scroller

Trying to create a list of todos using react-infinite-scroller. The list will display 20 todos, the next todos will be displayed while scrolling. I fetch Todos from 'https://jsonplaceholder.typicode.com/todos'. The fetched todos are saved in the todos variable.

I've modeled this example: https://github.com/CassetteRocks/react-infinite-scroller/blob/master/docs/src/index.js.

Demo here: https://cassetterocks.github.io/react-infinite-scroller/demo/.

I can not see Loading.. appearing and fetching further tasks.

Code here: https://stackblitz.com/edit/react-tcm9o2?file=index.js

import InfiniteScroll from 'react-infinite-scroller';
import qwest from 'qwest';

class App extends Component {

  constructor (props) {
    super(props);
    this.state = {
      todos: [],
      hasMoreTodos: true,
      nextHref: null
    }
  }

  loadTodos(page){
     var self = this;
    const url = 'https://jsonplaceholder.typicode.com/todos';

    if(this.state.nextHref) {
      url = this.state.nextHref;
    }

    qwest.get(url, {
      linked_partitioning: 1,
      page_size: 10
    }, {
      cache: true
    })
    .then((xhr, resp) => {
      if(resp) {
        var todos = self.state.todos;
        resp.map((todo) => {

          todos.push(todo);
        });

        if(resp.next_href) {
          self.setState({
            todos: todos,
            nextHref: resp.next_href
          });
        } else {
          self.setState({
              hasMoreTodos: false
          });
        }
      }
    });
  }


  render () {
    const loader = <div className="loader">Loading ...</div>;
    console.log(this.state.todos);

    var items = [];
    this.state.todos.map((todo, i) => {
        items.push(
            <div className="track" key={todo.id}>
              <p className="title">{todo.title}</p>
            </div>
        );
    });


    return (
      <InfiniteScroll
            pageStart={0}
            loadMore={this.loadTodos.bind(this)}
            hasMore={this.state.hasMoreTodos}
            loader={loader}>
        <div className="tracks">
          {items}
        </div>
      </InfiniteScroll>
    )
  }
}



from Creating a todos list using react-infinite-scroller

No comments:

Post a Comment