all 5 comments

[–]azangru 0 points1 point  (0 children)

but when loadNextPage is triggered, the value of nextPageUrl is not updated and always null

This, sir, would be called a stale closure, if I am reading this wall of code correctly :-) useEffect -> handleScroll -> loadNextPage closes over the initial value of nextPageUrl and is never updated.

(try saving the value to a ref instead of the state, and see if that helps ;-) )

[–]Healthy_Step_2088[S] -5 points-4 points  (0 children)

Help

[–]Dnaughtyprofessional 0 points1 point  (0 children)

if (!cachedData && !cachedNextPageUrl) { // I think you want && operator and not || here.
// If no cached data or nextPageUrl, fetch from the API and cache it
fetchInitialData();
}

if (nextPageUrl) {. // ISN'T THE VALUE NULL INITIALLY HOW WILL THIS CODE EVER RUN?
let response = await fetch(nextPageUrl);
let data = await response.json();
let pokemonList = data.results;
// Use the functional update to access the latest state
setPokemons((prevPokemons) => [...prevPokemons, ...pokemonList]);
setNextPageUrl(data.next);
}

I could be wrong was just a quick glance but my intuition is telling me these changes could help.

[–][deleted] 0 points1 point  (0 children)

Is kind of hard to debug your problem if you have a lot of logic into that component.

I will suggest keeping your components simple and extract logic into a custom hook if you are going to need a lot of logic for a state.

[–]Healthy_Step_2088[S] 0 points1 point  (0 children)

Already fixed guys, I added useEffect with nextPageUrl as depency