Skip to content

Instantly share code, notes, and snippets.

@asktree
Created March 18, 2020 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asktree/b415e793b1e74289917063e709c1f2f9 to your computer and use it in GitHub Desktop.
Save asktree/b415e793b1e74289917063e709c1f2f9 to your computer and use it in GitHub Desktop.
import React from "react"
import LinearProgress from "@material-ui/core/LinearProgress"
import throttle from "lodash.throttle"
import ScrollManager from "./ScrollManager"
import { Id, Result } from "../../modules/Stores/Search/searchInterfaces"
import Masonry from "./Masonry"
import { Typography } from "@material-ui/core"
interface Props {
setActiveInfoId(id: Id): void
setInfoOpen(open: boolean): void
items: Result[]
loadMore(): void
isLoading: boolean
isFinished: boolean
}
const InfiniteScroll = (Content) => ({
setActiveInfoId,
setInfoOpen,
items,
loadMore,
isLoading,
isFinished,
}: Props) => {
const sentinel = React.useRef<null | any>(null)
const threshold = 300
const scrollThrottle = 64
const onScroll = React.useCallback(
throttle(() => {
if (
sentinel.current &&
sentinel.current.getBoundingClientRect().top - window.innerHeight < threshold
) {
loadMore()
}
}, scrollThrottle),
[loadMore]
)
React.useEffect(() => {
window.addEventListener("scroll", onScroll)
return () => window.removeEventListener("scroll", onScroll)
}, [onScroll])
React.useEffect(() => {
onScroll() // in case the window isn't full of items yet
}, [items, onScroll])
React.useEffect(() => {
if (items.length === 0) {
loadMore()
}
}, [loadMore, items.length])
return (
<>
<ScrollManager />
<Content
setActiveInfoId={setActiveInfoId}
setInfoOpen={setInfoOpen}
items={items}
/>
<div ref={sentinel} key="sentinel" />
{isLoading ? <LinearProgress variant="query" color="secondary" /> : null}
{isFinished ? (
<Typography>Your query returned {items.length} results.</Typography>
) : null}
</>
)
}
export default InfiniteScroll(Masonry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment