I'm trying to do an infinite scroll with my data that is an array. Most examples I see uses an API call and it got pages included on it but I'm having trouble doing it with just an array and values to set how many objects to load per scroll. Here's my code.
import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import InfiniteScroll from 'react-infinite-scroll-component'
const Scroll = ({ tweets }) => {
const [allTweets, setAllTweets] = useState(tweets)
const [hasMore, setHasmore] = useState(true)
const [lastPosition, setLastPosition] = useState(0)
const perPage = 4
const loadProducts = () => {
setTimeout(() => {
setAllTweets(...allTweets, tweets.slice(lastPosition, lastPosition + perPage))
}, 4000)
setLastPosition(lastPosition + perPage)
}
useEffect(() => {
loadProducts()
}, [allTweets])
return (
<InfiniteScroll
dataLength={allTweets.length}
next={loadProducts}
hasMore={hasMore}
endMessage={
<p style={{ textAlign: 'center' }}>
<b>Yay! You have seen it all</b>
</p>
}
loader={<h4>Loading...</h4>}
>
<div className="flex flex-col">
{allTweets &&
allTweets.slice(lastPosition, lastPosition + perPage).map((value, index) => {
return <div className="py-10 px-5">{value.body}</div>
})}
</div>
</InfiniteScroll>
)
}
export default Scroll