I try to make some kind of infinite scroll
Here is my CodeSandbox setup (first approach)
To paginate I made some kind of cursor which keeps last loaded item id in after state variable
I use that after value in a handleLoadMore, which is passed as parameter to my custom LoadMore component. When page loaded, I can trigger first handleLoadMore with correct after value, but all following requests are uses it's first value (59 in my case)
I guess thats due to the fact that handleLoadMore is created during first render of LoadMore component. To proof it I added loading state variable, which controls wheither LoadMore component is rendered:
// App.tsx
...
export default function App() {
const [loading, setLoading] = useState(false);
...
const handleLoadMore = () => {
setLoading(true);
setTimeout(() => {
... // receive another batch
setLoading(false);
}
}
...
return (
...
// <LoadMore onLoadMore={handleLoadMore} />}
{!loading && <LoadMore onLoadMore={handleLoadMore} />}
...
)
}
You may check it here (second approach). And this variant works as I expect. That's because with every change of loading from true to false LoadMore component is rerendered, so it's handleLoadMore redefined with new after value. But I don't think this approach is correct - I want to keep LoadMore component visible all the time
What could be done is make onLoadMore handler parametric and pass after value to it like:
// LoadMore.tsx
...
interface LoadMoreProps {
// onLoadMore: () => void;
onLoadMore: (after: number) => void;
after: number
}
export default ({ onLoadMore, after }: LoadMoreProps) => {
useEffect(() => {
...
const observer = new IntersectionObserver((entries: any) => {
...
if (entry.isIntersecting) {
// onLoadMore();
onLoadMore(after);
}
}, options);
...
}, [loaderRef?.current]);
}
...
But I want to keep LoadMore component independent of my pagination technique (here I use some kind of cursor, but it might be page index or whatever)
So, what is the reason for such behaviour in my first approach? Is there any way clean and proper to make onLoadMore use actual value of after variable?
There is also an side question, but I will ask it here - after triggering handleLoadMore page freezes for a few moments - may be feelable if you scroll to bottom and immideately scroll to top - it will not respond, cannot fugure out why