Infinite Scroll using Cells

Hi all!

I’m currently working on an app that requires infinite scroll. (So fetching the next “page” when reaching the end of the screen).

I tried doing this using fetchMore inside a Cell, to see how it would work.

According to my observations 2 options are possible:

  1. You set notifyOnNetworkStatusChange to true and the loading screen retriggers, hiding the already loaded content and showing your Loading component.
  2. You leave notifyOnNetworkStatusChange on false and there’s no loading screen, your content just appears at some point.

I would like to display a loader on the bottom of my screen while new content loads. To facilitate this I’ve created the following intermediary component:

import StoriesCell from 'src/components/StoriesCell'

import { useState, useCallback, useEffect } from 'react'

export const StoriesInfinite = ({ limit, where }) => {
  const [cursors, setCursors] = useState({})

  const addCursor = useCallback(newCursor => {
    setCursors(current => ({ ...current, [newCursor]: true }))
  }, [])

  useEffect(() => {
    setCursors({})
  }, [where])

  return (
    <>
      <StoriesCell first={limit} where={where} onReachingEnd={addCursor} />
      {Object.keys(cursors).map(cursorId => (
        <StoriesCell
          key={cursorId}
          first={limit}
          after={{ id: cursorId }}
          where={where}
          onReachingEnd={addCursor}
        />
      ))}
    </>
  )
}

What it does is add a cursor to a list of cursors (made unique by using an Object, to prevent duplication). Each cursor/page then renders it’s own Cell.

It works pretty well for me!

Since infinite scrolling is a quite common functionality nowadays I decided to open a topic to ask what you think. Is there anything I missed int he fetchMore method? I wasn’t familiar with it before! Is there an easier way to do this?

2 Likes

Hi @Robert I’ve not tried to do something like this as it’s definitely the first use-case I’ve seen, but at first glance, this is a great example/use-case! Appreciate you posting here for others to see and for discussion.

@peterp quick reactions about improving this or potential downsides?

This is like more than a year later - sorry, but I was wondering how you got fetchmore working with Apollo? I’m not sure what the redwood client does OOTB with merging