Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active October 29, 2018 03:27
Show Gist options
  • Select an option

  • Save itsMapleLeaf/aae4cde0381b561457b6b4f998dc6a67 to your computer and use it in GitHub Desktop.

Select an option

Save itsMapleLeaf/aae4cde0381b561457b6b4f998dc6a67 to your computer and use it in GitHub Desktop.
Infinite Lists with React Hooks, concept
import React, { useState } from "react"
export default function InfiniteList() {
// have a list of "pages" in our state
const [pages, setPages] = useState([])
// the number of items we have per page
const count = 20
// this function should be called whenever the user wants to "move on" in the list
// that is, move onto the next page
// we take the offset of the previous page and say we want the next 20 items after that for the next one
// the only missing piece here is to figure out when to stop adding pages 🤔
// that would probably require fetching the data here instead of in InfiniteListPage
function addNewPage() {
const lastPage = pages[pages.length - 1]
const newPage = {
count,
offset: lastPage ? lastPage.offset + count : 0,
}
setPages([...pages, newPage])
}
return (
// this is an imaginary component which calls onEndReached when we scroll to the bottom
<InfiniteListView pages={pages} onEndReached={addNewPage}>
{pages.map((page) => (
// render a page for each page we have in state
<InfiniteListPage page={page} />
))}
</InfiniteListView>
)
}
function IntiniteListPage(props) {
// use the page prop we've been given to fetch all of the items for this page from some react-cache resource
const items = pageResource.read(props.page)
return items.map(renderPage)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment