0

I am trying to fetch data after I scroll down at the bottom of the element. This part is working that it fetches when I scroll, but the behavior is not correct. When it fetches, the data renders so many times and also not in right order. It looks fine before I scroll. It shouldn't do that. I am using MobX.

The problem must be in reaction somehow:

componentDidMount() {
const { listData } = this.props;
const { data = [] } = listData;
const rowData = [...data].reverse();

this.ref.current.addEventListener('scroll', this.handleScroll, false);
this.handleScroll();

reaction(
  () => rowData,
  () => this.handleScroll()
); }

And render looks like this:

render() {
    const { listData } = this.props;
    const { data = [] } = listData;
    const rowData = [...data].reverse();

    return (
      <>
        <div className="container" ref={this.ref}>
          <ul className="list">
            {_.map(rowData, (item, index) => (
              <li
                className="some-list"
                key={index}
              >
                <div className="item-wrapper">
                  <div className="item">
                    <div className="item-name">
                      List {item.number}
                    </div>
                  </div>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </>

Code for handle scroll:

  handleScroll() {
    const { listData } = this.props;
    const { paging = [] } = listData;

    const contentHolder = this.ref.current;
    const margin = 100;
    const scrollY = contentHolder.scrollTop;
    const wrapperHeight = contentHolder.offsetHeight;

    const list = contentHolder.querySelector('.container');

    if (wrapperHeight + scrollY >= list.offsetHeight - margin) {
      this.handleRecieveFetch(paging.next);
    }
  }

The code is in the same component. Do you have any ideas what I am doing wrong?

IssaChii
  • 55
  • 1
  • 9
  • Could you add code for `handleScroll`? I am not sure that you need `reaction` at all, you should probably fetch data inside `handleScroll` and that's it. You don't need to react to `rowData` change. This reaction probably not working at all since you destructure array and make it regular array, not observable. – Danila Aug 24 '20 at 10:34
  • @Danila I've added the handleScroll :) – IssaChii Aug 24 '20 at 10:44
  • It might be because you don't have any throttling for this handler. So every time user scrolls `handleScroll` is invoked several times and `handleRecieveFetch` might be invoked lots of times too. You can add `console.log` inside `if` and check how many times it is called. If this is the case then you need to add some handling to prevent loading data again while it is still in loading state. – Danila Aug 24 '20 at 10:50
  • @Danila I am actually using throttling. and I have also used console.log inside the if. And it shows up after every scroll is on the bottom. :) – IssaChii Aug 24 '20 at 10:56

0 Answers0