Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

481
Views
React Infinite scroll component not working properly

I am using react-infinite scroll component like this:

const [hasMore, setHasMore] = useState(true)
const [pageNumber, setPageNumber] = useState(1)

  const fetchDataOnScroll = async () => {
    try {
      const res = await axios.get(
        `${process.env.REACT_APP_API}/api/v1/posts?page=${pageNumber}`
        
      )
  
      (res.data.doc.length === 0) setHasMore(false)

      setPosts((prev) => [...prev, ...res?.data?.doc])
      setPageNumber((prev) => prev + 1)
    } catch (error) {
      alert('Error fetching Posts')
      console.log('ERROR', error.data.response)
    }
  }

  return (
<InfiniteScroll
   hasMore={hasMore}
   next={fetchDataOnScroll}
   endMessage='No More Post'
   dataLength={posts.length}
   loader={<h1>LOADING...</h1>}
>
{posts.map((post) => (
 <FeedCard key={post._id} post={post} />
))}
 </InfiniteScroll>
)

I only get LOADING... on my browser. But when I write my next as next={fetchDataOnScroll()}, It renders continuously until the page freezes. I have to close my browser.

How can i fix this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I suggest using useEffect and change page in next function. I think this make some amount of delay that allow infinite scroll render current component. This code solve my problem.

<InfiniteScroll
   ...
   next={setPage(page+1)}
...>

And in useEffect function after changing page you can call api

useEffect(() => {
fetchDataOnScroll()
},[page]
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!