DEV Community

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

Collapse
 
rockwell profile image
Ahmad khattab

I would add another target, that is the messages container. Then, proceed to modify the scroll method to look like this

  async scroll() {
    if (this.chatTarget.scrollTop < 100 && !this.fetching && !this.hasLastPageTarget) {

      this.fetching = true
      await get(this.urlValue, {
        responseKind: "turbo-stream",
        query: {
          page: this.pageValue
        }
      });

      this.pageValue += 1;
      this.fetching = false
    }
  }

Enter fullscreen mode Exit fullscreen mode

PS. you might want to scroll the container when it loads. You can do so in the initialize method

  initialize() {
    this.scrollToBottom();
    super.initialize();
  }

  scrollToBottom() {
   this.inboxTarget.scroll({
        top: this.inboxTarget.scrollHeight,
        behavior: this.messageSent ? "smooth" : "instant",
      });
  }
Enter fullscreen mode Exit fullscreen mode