Skip to content

Commit

Permalink
feat: Comment InfiniteScroll 적용 및 Hook 추가(#80)
Browse files Browse the repository at this point in the history
- usePageCounter Hook
- Comment Infinite Scroll 추가
  • Loading branch information
ByungJin-Lee committed Nov 9, 2022
1 parent 5e80153 commit c8c9cb4
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 9 deletions.
27 changes: 18 additions & 9 deletions src/components/Comment/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import CommentRepo from '../../utils/commentRepo';
import { useEffect } from 'react';
import { useWindowEvent } from '../../hooks/useWindowEvent';
import { isBottomPosIn } from '../../utils/scroll';
import usePageCounter from '../../hooks/usePageCounter';

type Props = {
articleId: any;
Expand All @@ -28,18 +29,26 @@ const Comment = ({ articleId }: Props) => {
operator,
);

const { isBlocked, getNextCursor, confirmNextCursor } = usePageCounter();

const fetchNext = async () => {
if (!isBlocked()) {
if (await fetchComment(getNextCursor())) confirmNextCursor();
}
};

useEffect(() => {
fetchComment(1);
fetchNext();
}, []);

// useWindowEvent(
// ['scroll'],
// debounce((_) => {
// if (isBottomPosIn(50) && isNext()) {
// fetchNext();
// }
// }, 100),
// );
useWindowEvent(
['scroll', 'wheel'],
debounce((_) => {
if (isBottomPosIn(50)) {
fetchNext();
}
}, 100),
);

return (
<List sx={{ width: '100%', maxWidth: 360, bgcolor: 'background.paper' }}>
Expand Down
1 change: 1 addition & 0 deletions src/hooks/useCommentReducer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ function handleFromDispatch(
type: 'ASSIGN',
payload: [...state.comments, ...coming.map(commentMapping)],
});
return Array.isArray(coming) && coming.length > 0;
},
async expand(commentId: number) {
const [selected, index] = getUIComment(state.comments, commentId);
Expand Down
30 changes: 30 additions & 0 deletions src/hooks/usePageCounter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useRef } from 'react';

export default function usePageCounter(initialCursor = 0) {
const page = useRef<{ cursor: number; blocked: boolean }>();

if (!page.current)
page.current = {
cursor: initialCursor,
blocked: false,
};

return {
isBlocked() {
return page.current ? page.current.blocked : true;
},
getNextCursor() {
if (page.current) {
page.current.blocked = true;
return page.current.cursor + 1;
}
return initialCursor;
},
confirmNextCursor() {
if (page.current) {
page.current.cursor += 1;
page.current.blocked = false;
}
},
};
}

0 comments on commit c8c9cb4

Please sign in to comment.