Skip to content

Commit

Permalink
FEAT : 무한 스크롤 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
junvhui committed Feb 24, 2024
1 parent 55c30e1 commit 6486b18
Show file tree
Hide file tree
Showing 4 changed files with 368 additions and 39 deletions.
12 changes: 1 addition & 11 deletions backend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,9 @@ async function connectToMongoDB() {

connectToMongoDB();

const PAGE_SIZE = 3;

app.get('/article', async (req, res) => {
const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1;

try {
const articles = await articleCollection
.find({})
.sort({ _id: -1 }) // _id를 기준으로 역순으로 정렬
.skip((pageNumber - 1) * PAGE_SIZE)
.limit(PAGE_SIZE)
.toArray();

const articles = await articleCollection.find({}).toArray();
res.json({ result: 'success', article: articles });
} catch (error) {
console.error('Error fetching articles:', error);
Expand Down
73 changes: 73 additions & 0 deletions backend/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
const express = require('express');
const { MongoClient } = require('mongodb');
const cors = require('cors');

const app = express();
app.use(express.json());
app.use(cors());

const uri = 'mongodb+srv://sparta:[email protected]/?retryWrites=true&w=majority';
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

let db, articleCollection, rankCollection, transferCollection;

async function connectToMongoDB() {
try {
await client.connect();
console.log('Connected to MongoDB');

db = client.db('kickoff');
articleCollection = db.collection('article');
rankCollection = db.collection('rank');
transferCollection = db.collection('transfer');
} catch (error) {
console.error('Error connecting to MongoDB:', error);
}
}

connectToMongoDB();

const PAGE_SIZE = 3;

app.get('/article', async (req, res) => {
const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1;

try {
const articles = await articleCollection
.find({})
.sort({ _id: -1 }) // _id를 기준으로 역순으로 정렬
.skip((pageNumber - 1) * PAGE_SIZE)
.limit(PAGE_SIZE)
.toArray();

res.json({ result: 'success', article: articles });
} catch (error) {
console.error('Error fetching articles:', error);
res.status(500).json({ result: 'error', message: 'Internal server error' });
}
});

app.get('/rank', async (req, res) => {
try {
const ranks = await rankCollection.find({}).toArray();
res.json({ result: 'success', rank: ranks });
} catch (error) {
console.error('Error fetching ranks:', error);
res.status(500).json({ result: 'error', message: 'Internal server error' });
}
});

app.get('/transfer', async (req, res) => {
try {
const transfers = await transferCollection.find({}).toArray();
res.json({ result: 'success', transfer: transfers });
} catch (error) {
console.error('Error fetching transfers:', error);
res.status(500).json({ result: 'error', message: 'Internal server error' });
}
});

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
39 changes: 11 additions & 28 deletions src/MainPage/List.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { useState, useEffect } from 'react';
import { useState, useRef, useEffect } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import { useSearchParams } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';

import { useInView } from 'react-intersection-observer';

interface PostProps {
title: string;
content: string;
Expand Down Expand Up @@ -197,35 +195,21 @@ const Post = () => {
const [filterData, setFilterData] = useState<PostProps[]>([]);

// 이적 기사 최신순 정렬
const r_articleData = [...articleData].reverse();
const r_filterData = [...filterData].reverse();

console.log(articleData);

// Intersection Observer를 이용하여 무한 스크롤 감지
const [pageNumber, setPageNumber] = useState(1);
const [ref, inView] = useInView();

useEffect(() => {
if (inView) {
// 뷰포트에 진입하면 페이지 번호를 증가시켜 새로운 데이터 요청
setPageNumber((prevPageNumber) => prevPageNumber + 1);
console.log(pageNumber);
}
}, [inView]);

// 이전 코드와 동일하게 axios를 이용하여 데이터를 가져옴
// 이적 기사 GET 요청
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(`/article?pageNumber=${pageNumber}`);
const newData = response.data.articles;
setArticleData((prevData) => [...prevData, ...newData]); // 기존 데이터와 새로운 데이터 결합
const response = await axios.get('/article');
setArticleData(response.data.article);
} catch (error) {
console.error('Error fetching user data:', error);
}
};

fetchData();
}, [pageNumber]); // 페이지 번호가 변경될 때마다 실행
}, []);

let [query, setQuery] = useSearchParams();

Expand All @@ -252,8 +236,8 @@ const Post = () => {
</TitleWrap>
<PostContent>
{teamName ? (
filterData.length > 0 ? (
filterData.map((post, index) => (
r_filterData.length > 0 ? (
r_filterData.map((post, index) => (
<PostContainer key={index} onClick={() => handlePostContainerClick(post.content)}>
<Team className="team">{post.team}</Team>
<PostImage style={{ backgroundImage: `url(${post.url})` }} />
Expand All @@ -263,8 +247,8 @@ const Post = () => {
) : (
<EmptyContainer>해당 팀의 기사가 없습니다.</EmptyContainer>
)
) : articleData.length > 0 ? (
articleData.map((post, index) => (
) : r_articleData.length > 0 ? (
r_articleData.map((post, index) => (
<PostContainer key={index} onClick={() => handlePostContainerClick(post.content)}>
<Team className="team">{post.team}</Team>
<PostImage style={{ backgroundImage: `url(${post.url})` }} />
Expand All @@ -274,7 +258,6 @@ const Post = () => {
) : (
<EmptyContainer>기사가 없습니다.</EmptyContainer>
)}
<div ref={ref}></div>
</PostContent>
</PostWrap>
);
Expand Down
Loading

0 comments on commit 6486b18

Please sign in to comment.