So I found that this is the problem with so many of developers using React-Infinite-Scroll-Component
, but haven’t found a solution yet! I guess the fetchData
won’t work after the second run of loading. Can somebody please help me with this?
This is the link to my SandBox demo: enter link description here
But I’ll add the code for convenience too. This is my NameList
Component which the Infinite Scroll is placed in:
function NameList() {
const [namesList, setNamesList] = useState([]);
const [noMore, setNoMore] = useState(true);
const [page, setPage] = useState(2);
useEffect(() => {
const getNames = async () => {
const res = await fetch(
`https://r3py2q-3000.csb.app/users?_page=1&_limit=20`,
);
const data = await res.json();
setNamesList(data);
};
getNames();
}, []);
console.log(namesList);
const fetchNames = async () => {
const res = await fetch(
`https://r3py2q-3000.csb.app/users?_page=${page}&_limit=20`,
);
const data = await res.json();
return data;
};
const fetchData = async () => {
const namesFromServer = await fetchNames();
setNamesList([...namesList, ...namesFromServer]);
if (namesFromServer.length === 0 || namesFromServer.length < 20) {
setNoMore(false);
}
setPage(page + 1);
};
const namesToShow = namesList;
return (
<div>
<Box
sx={{
overflowY: "scroll",
height: "30rem",
}}
>
<InfiniteScroll
dataLength={namesList.length}
next={fetchData}
hasMore={noMore}
loader={<h4>Loading...</h4>}
endMessage={
<b>End of names!</b>
}
>
<List>
{namesToShow.map(({ first, last }, index) => (
<ListItem key={index} divider>
<ListItemText primary={first} secondary={last} />
</ListItem>
))}
</List>
</InfiniteScroll>
</Box>
</div>
);
}