본문 바로가기

프로젝트/I들 ChangeArt

머신러닝 프로젝트 - 프론트 페이지네이션 구현

1. 수정된 백엔드 코드로 인해 바뀐 response 데이터 찾기 

 문제점

잘 작동하던 loadArticles()함수에서 에러 발생

Uncaught (in promise) TypeError: articles.forEach is not a function
    at loadArticles (index.js:30:14)

 시도해 본 것들

forEach에 대해서 찾아보기 

Array.from(articles).forEach(article => {
        // articles.forEach(article => {
        console.log(articles, article)

검색으로 유사 배열이라는 검색 결과를 얻음 

Array.from 추가시 에러는 사라졌지만, console.log도 반응이 없는 상태

 해결 방법

백엔드의 코드가 수정됐음을 깨닫고 console.log()로 확인해보기 

기존 데이터

[
    {
        "id": 23,
        "user": "폼데이터닉네임",
        "user_id": 1,
        "like_count": 0,
        "comments": [],
        "image": null,
        "title": "제목3",
        "content": null,
        "created_at": "2023-05-25T19:00:41.253135+09:00",
        "updated_at": "2023-05-25T19:00:41.253135+09:00"
    },
    {
        "id": 22,
        "user": "폼데이터닉네임",
        "user_id": 1,
        "like_count": 0,
        "comments": [],
        "image": null,
        "title": "제목3",
        "content": null,
        "created_at": "2023-05-25T19:00:40.693473+09:00",
        "updated_at": "2023-05-25T19:00:40.693473+09:00"
    }
]

바로 게시글의 리스트가 담겨온다. 

{
    "count": 23,
    "next": "http://127.0.0.1:8000/home/?page=2",
    "previous": null,
    "results": [
        {
            "id": 23,
            "user": "폼데이터닉네임",
            "user_id": 1,
            "like_count": 0,
            "comments": [],
            "image": null,
            "title": "제목3",
            "content": null,
            "created_at": "2023-05-25T19:00:41.253135+09:00",
            "updated_at": "2023-05-25T19:00:41.253135+09:00"
        },
        {
            "id": 22,
            "user": "폼데이터닉네임",
            "user_id": 1,
            "like_count": 0,
            "comments": [],
            "image": null,
            "title": "제목3",
            "content": null,
            "created_at": "2023-05-25T19:00:40.693473+09:00",
            "updated_at": "2023-05-25T19:00:40.693473+09:00"
        }
    ]
}

results안에 articles의 값들이 담겨서 온다. 

 

기존에 확인하던 response_json에서 .results 추가하기 

[
    {
        "id": 23,
        "user": "폼데이터닉네임",
        "user_id": 1,
        "like_count": 0,
        "comments": [],
        "image": null,
        "title": "제목3",
        "content": null,
        "created_at": "2023-05-25T19:00:41.253135+09:00",
        "updated_at": "2023-05-25T19:00:41.253135+09:00"
    },
    {
        "id": 22,
        "user": "폼데이터닉네임",
        "user_id": 1,
        "like_count": 0,
        "comments": [],
        "image": null,
        "title": "제목3",
        "content": null,
        "created_at": "2023-05-25T19:00:40.693473+09:00",
        "updated_at": "2023-05-25T19:00:40.693473+09:00"
    }
]

기존에 사용하던 형식으로 바로 받을 수 있었다.

 알게 된 점

백엔드와 프론트를 연결하는 작업에서 작동하던 코드가 갑자기 이상을 보인다면 전달되는 데이터가 바뀐 것인지 확인해보자 

 

2. 프론트에서 페이지네이션 구현

 문제점

postman의 환경에서 페이지네이션이 가능한 것을 확인했지만, 프론트는 아직 확인하지 못 함

 시도해 본 것들

담겨오는 데이터 확인하기

{
    "count": 23,
    "next": "http://127.0.0.1:8000/home/?page=2&undefined=",
    "previous": null,
    "results": [
        {
            "id": 23,
            "user": "폼데이터닉네임",
            "user_id": 1,
            "like_count": 0,
            "comments": [],
            "image": null,
            "title": "제목3",
            "content": null,
            "created_at": "2023-05-25T19:00:41.253135+09:00",
            "updated_at": "2023-05-25T19:00:41.253135+09:00"
        },
        {
            "id": 22,
            "user": "폼데이터닉네임",
            "user_id": 1,
            "like_count": 0,
            "comments": [],
            "image": null,
            "title": "제목3",
            "content": null,
            "created_at": "2023-05-25T19:00:40.693473+09:00",
            "updated_at": "2023-05-25T19:00:40.693473+09:00"
        }
    ]
}

next에서 ?page=2를 가져오면 가능할 것으로 보임

async function nextPage() {
    const response = await fetch(`${backend_base_url}/home/`, {
    })
    const response_json = await response.json()
    console.log('다음 페이지 클릭')
    if (response_json.next) {
        location.href = `${frontend_base_url}/index.html${response_json.next.split('/')[4]}`
    } else {
        alert('다음 페이지가 없습니다.')
    }
}

next를 split해서 ?부분부터 추출 

 

2페이지에서 이동하지 못하는 이슈 발생

const response = await fetch(`${backend_base_url}/home/`, {})

링크가 최초 홈페이지 접속시 링크로 설정되어 최대 2페이지까지만 넘어갈 수 있었다.

 

const currentPage = '?' + document.location.href.split('?')[1]

const response = await fetch(`${backend_base_url}/home/${currentPage}`, {})

이동할 페이지 뿐만아니라 현재 페이지에 대한 정보도 .location.href로 확인 

 해결 방법

// 게시글 리스트 불러오기 
async function getArticles() {
    const response = await fetch(`${backend_base_url}/home/${currentPage}`, {
    })
    if (response.status == 200) {
        const response_json = await response.json()
        console.log(response_json)
        console.log(response_json.results)
        return response_json.results
    } else {
        alert('게시글 로딩 실패')
    }
}

// 페이지네이션
// 이전 페이지 보기
async function previousPage() {
    const response = await fetch(`${backend_base_url}/home/${currentPage}`, {
    })
    const response_json = await response.json()
    console.log('이전 페이지 클릭')
    if (response_json.previous) {
        location.href = `${frontend_base_url}/index.html${response_json.previous.split('/')[4]}`
    } else {
        alert('이전 페이지가 없습니다.')
    }
}
// 다음 페이지 보기
async function nextPage() {
    const response = await fetch(`${backend_base_url}/home/${currentPage}`, {
    })
    const response_json = await response.json()
    console.log('다음 페이지 클릭')
    if (response_json.next) {
        location.href = `${frontend_base_url}/index.html${response_json.next.split('/')[4]}`
    } else {
        alert('다음 페이지가 없습니다.')
    }
}

 알게 된 점

어떻게 진행해야할지 스스로 정하고 거기에 필요한 코드를 찾아보면서 아직 낯선 js지만 사용된 코드를 이해할 수 있었다.

아직 모든 이슈를 해결하지 못했다.

"next": "http://127.0.0.1:8000/home/?page=2&undefined=",

postman과 다르게 '&undefined='가 붙는 것을 보면 무언가 내 생각과 다르게 작동하고 있는 코드가 있고 나중에 문제가 될 수 있다는 뜻이다.