nick
nick

Reputation: 1178

useEffect calling function infinitely

I have a function that fetches and dispays data. I need this function to be called twice, once when the page loads and when InfiniteScroll calls it. The problem is that when getData is called by useEffect it goes on forever.

Code:

const getData = async(page) => {
    const CancelToken = axios.CancelToken;
    const source = CancelToken.source();
    
    axios.get(`/api?page=${page}&limit=10`, { cancelToken: source.token })
    .then(res => {
        setProducts(prevProducts => {
            return [...new Set([...prevProducts, ...res.data])]
        })     
        setHasMore(res.data.length > 0)

        console.log(res.data)
    }).catch(e => {
        if (axios.isCancel(e)) return 
    })
}

useEffect(() => {
    getData()
}, [getData])

const handlePagination = () => {
    setPage(page + 1)
}

 ...

   <InfiniteScroll
      dataLength={products.length}
      next={handlePagination}
      hasMore={hasMore}
    >
     ... 
   </InfiniteScroll>
   

When getData gets called by useEffect it goes forever. Just to note I'm using react-infinite-scroll-component.

Upvotes: 1

Views: 125

Answers (2)

Zunayed Shahriar
Zunayed Shahriar

Reputation: 2723

Your effect will be changed as:

useEffect(() => {
    getData()
}, [page])

So that, when the page changes, I mean scrolling ends, new data will be fetched.

You were facing infinite loops because you were getting data on getting data. Sounds weird but it happened.

Upvotes: 4

AIR ALPHA
AIR ALPHA

Reputation: 44

Try to change your useEffect like this

useEffect(() => {
 getData(),
 return () => {}
}, [])

Upvotes: 0

Related Questions