export default function Foo() {
const [items, setItems] = useState([]);
const [page, setPage] = useState(0)
useEffect(() => {
fetchData();
}, []);
function fetchData() {
axios
.get("http://localhost:4000/api/getcontent?page=" + page)
.then((res) => {
setPage(page + 1)
setItems((items) => [...items, ...res.data])
}).catch((err) => console.log(err));
}
function refresh() {
setPage(0)
setItems([])
}
return (
<InfiniteScroll
next={fetchData}
refreshFunction={refresh}
pullDownToRefresh
pullDownToRefreshThreshold={50}
pullDownToRefreshContent={
<h3 style={{ textAlign: 'center' }}>↓ Pull down to refresh</h3>
}
releaseToRefreshContent={
<h3 style={{ textAlign: 'center' }}>↑ Release to refresh</h3>
}>
</InfiniteScroll>
);
};
I got an infinite scroll component that, upon refresh will call the “refresh” function. This refresh function currently simply sets the page number. It does not work. The page will be stuck at loading. However, if I replace the refresh function with a copy of fetchData, then everything works just fine. Why is this?
instead of just resetting the state, you can trigger fetchData after resetting the state.
function refresh() {
setPage(0);
setItems([]);
setTimeout(() => fetchData(), 0); // Trigger fetch after reset
}
Ensure that your useEffect is correctly set to trigger when page changes,
useEffect(() => {
fetchData();
}, [page]);
also check if the fetchData function is being called as expected by adding a console.log inside it or inspecting the network requests in your browser’s developer tools. let me know if it worked 🙂