Reputation: 1178
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
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
Reputation: 44
Try to change your useEffect like this
useEffect(() => {
getData(),
return () => {}
}, [])
Upvotes: 0