7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

react-infinite-scrollerで、loadMoreが2度動く場合の対処法

Posted at

発生した事象

react-infinite-scrollerで無限スクロールを実装していると、
loadMoreが2度動いてしまい、表示するデータを格納するstateに重複データが格納されるという挙動に悩まされました。

対処法

こちらのIssueに対処法がありました。

  1. データをFetch中かどうかを判定するstateを追加

const [isFetching, setIsFetching] = useState(false);


2. 追加したstateを判定条件に加える

    ```typescript
    <InfiniteScroll
      pageStart={0}
      loadMore={fetchData}
      hasMore={!isFetching && hasMoreTracks} // isFetchingを判定条件に追加
      initialLoad={true}
      loader={<div key={0}>Loading ...</div>}
      useWindow={false}
    >
      {items}
    </InfiniteScroll>
    ```
 
3. loadMoreに設定するデータ取得処理で`isFetching`のstateを操作

  ```typescript
  const fetchData = async () => {
    try {
      setIsFetching(true);
      {
        /* データ取得処理 */
      }
    } finally {
      setIsFetching(false);
    }
  };

まとめ

画面の一番下までスクロールした場合に、loadMoreが実行される機構なので、
初回のDOM生成時に誤作動を起こす可能性があるとのこと。

同じ問題にハマった人の助けになると嬉しいです。

7
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?