fetch new data in hasMore #9
Answered
by
buzinas
ALi-Hosseinzad
asked this question in
Q&A
-
How is it possible to fetch new data from the new API again in the |
Beta Was this translation helpful? Give feedback.
Answered by
buzinas
Dec 15, 2020
Replies: 1 comment
-
You need to add the API call as a side effect that depends on import React from 'react';
import useInfiniteScroll from '@closeio/use-infinite-scroll';
export default function MyComponent() {
const [items, setItems] = useState([]);
const [hasMore, setHasMore] = useState(false);
const [page, loaderRef, scrollerRef] = useInfiniteScroll({ hasMore });
// This effect runs every time `page` changes
useEffect(async () => {
const data = await myApiCall({ page });
setHasMore(data.hasMore);
setItems(prev => [...prev, data.items]);
}, [page]);
return (
<div ref={scrollerRef}>
{items.map(item => (
<div key={item.id}>{item.name}</div>
))}
// The `<div>` below will only render if `hasMore` is `true`. Our hook
// observes this `<div>` and as soon as it gets visible on the screen, we
// change the `page`, which triggers the effect again, re-fetching the API.
{hasMore && <div ref={loaderRef}>Loading…</div>}
</div>
);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
buzinas
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You need to add the API call as a side effect that depends on
page
returned by the hook. And you also need a component that renders in casehasMore
istrue
. Look at the example below: