DEV Community

Discussion on: Infinite Scroll with HOTWire - Part 2: Adding Stimulus

Collapse
 
ozovalihasan profile image
Hasan Özovalı • Edited

Thanks a lot for your article.

I noticed one issue. It is requesting the same page multiple times. So, let me share my suggestion to solve this issue.

# posts/index.html.erb
<div
  id="posts"
  data-controller="pagination"
  data-pagination-url-value="<%= posts_path %> "
  data-pagination-page-value="<%= 2 %>"
  data-pagination-request-value="false"
>
  <%= render @posts %>
</div>

Enter fullscreen mode Exit fullscreen mode
// pagination_controller.js
  static values = {
    url: String,
    page: Number,
    request: Boolean,
  };

  scroll() {
    if (!this.requestValue && this.scrollReachedEnd && !this.hasLastPageTarget) {
      this._fetchNewPage();
    }
  }

  async _fetchNewPage() {
    const url = new URL(this.urlValue);
    url.searchParams.set('page', this.pageValue)
    this.requestValue = true;
    await get(url.toString(), {
      responseKind: 'turbo-stream'
    });
    this.requestValue = false;
    this.pageValue +=1;
  }


Enter fullscreen mode Exit fullscreen mode