Yash Sharma
Yash Sharma

Reputation: 232

Infinite scroll in React

I'm trying to add infinite scroll in my component. I somehow did it but it is not working as expected. Whenever, I scroll to bottom it adds more data to APIData but it just duplicates the data which has been already fetched instead of adding new data. And, even when I'm at bottom, the scroll function still runs and fetching the data again and again which has already been fetched. And I'm also getting a warning that I didn't include getData in the dependency array. What's happening and why?

export default function News({ category }) {

    const [APIData, setAPIData] = useState([])

    const [page, setPage] = useState(1)

    const pageSize = 20

    async function getData() {
        let response = await fetch(`https://newsapi.org/v2/top-headlines?country=in&category=${category}&pageSize=${pageSize}&page=${page}&apiKey={APIKey}`)
        let parsedResponse = await response.json()
        setAPIData(APIData.concat(parsedResponse.articles))
    }

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

    window.addEventListener('scroll', function () {
        if (window.innerHeight + document.documentElement.scrollTop === document.scrollingElement.scrollHeight && page === 1) {
            setPage(2)
            getData()
            console.log('working')
        }
    }
    )

Upvotes: 1

Views: 302

Answers (2)

Muhammad Usama Ashraf
Muhammad Usama Ashraf

Reputation: 564

It can be most likely due to this https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

You can verify that what the page no while in the getData function by console

async function getData(category,page) {
    let response = await fetch(`https://newsapi.org/v2/top-headlines?country=in&category=${category}&pageSize=${pageSize}&page=${page}&apiKey={APIKey}`)
    let parsedResponse = await response.json()
    setAPIData(APIData.concat(parsedResponse.articles))
}

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

window.addEventListener('scroll', function () {
    if (window.innerHeight + document.documentElement.scrollTop === document.scrollingElement.scrollHeight && page === 1) {
        setPage(2)

        console.log('working')
    }
}

Upvotes: 2

poPaTheGuru
poPaTheGuru

Reputation: 1100

Add new items to state as follow:

setAPIData(previousState => [...previousState, ...parsedResponse.articles]) 

Upvotes: 1

Related Questions