I wanna load the first batch of comments immediately (using useEffect
) and then load additional pages when a "load more" button is pressed.
The problem is that my current setup causes an infinite loop (caused by the dependency on comments
).
If I remove the fetchNextCommentsPage
function from the useEffect
dependency list, everything seems to work, but EsLint complains about the missing dependency.
const [comments, setComments] = useState<CommentModel[]>([]);
const [commentsLoading, setCommentsLoading] = useState(true);
const [commentsLoadingError, setCommentsLoadingError] = useState(false);
const [paginationEnd, setPaginationEnd] = useState(false);
const fetchNextCommentsPage = useCallback(async function () {
try {
setCommentsLoading(true);
setCommentsLoadingError(false);
const continueAfterId = comments[comments.length - 1]?._id;
const response = await BlogApi.getCommentsForBlogPost(blogPostId, continueAfterId);
setComments([...comments, ...response.comments]);
setPaginationEnd(response.paginationEnd);
} catch (error) {
console.error(error);
setCommentsLoadingError(true);
} finally {
setCommentsLoading(false);
}
}, [blogPostId, comments])
useEffect(() => {
fetchNextCommentsPage();
}, [fetchNextCommentsPage]);