ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 86 TIL
    내일배움캠프 2023. 3. 2. 22:26

     

    프론트 작업을 마저 이어 갔는데 오늘 맡은 기능은 2개 입니다

    이렇게 정리하니까 하루동안 뭘한건가 싶네요 ...;;

     

    1. 좋아요 누른 게시글, 참가 신청 게시물 이동 버튼 활성화 

    2. 로그인 한 유저와 게시글 작성 유저 id 값이 같을 때 수정 버튼 활성화 및 다를 때 참가 신청 버튼 활성화

     

    1번은 30분 걸렸나? 처음엔 /page 가 아닌 백엔드 url 을 넣어서 처리하려다 시간을 좀 날려먹었고

    이동할 url 을 넣어서 간단히 처리했습니다. 

    function movePost(postId) {
        window.location.href = `/page/partypost?partypostId=${postId}`;
    }

     

     

    2번을 처리하는 과정에서 문제가 발생했습니다. 일단 로그인한 유저의 값을 어떻게 가져올까 생각했고 쿠키에서 토큰 값을 가져와야겠다 판단했고 아래 코드로 id 값을 가져왔습니다.

    const token = getCookieValue('Authorization');
    const tokenParts = token.split('.');
    const tokenPayload = JSON.parse(atob(tokenParts[1]));
    const loginUserId = tokenPayload.id;
    console.log(loginUserId)

    console.log 는 프론트는 아직 응애 수준이라 값이 http에 재대로 찍히는지 확인하려고 넣어놨습니다 

     

    로그인한 유저의 값을 가져왔으니 이제 if 문을 통해서 비교하여 해당 버튼의 상태를 변경하려 했습니다.

    if (loginUserId !== userId) {
        document.getElementById(`updatePost`).display.style.display = 'none';
    }

    이상하게 버튼의 상태는 바뀌지 않았고 전체글이 보이거나 안보이게 끔만 설정이 되는겁니다.

    그때까진 간과했던게 ajax 는 동적 프로그래밍으로 정적 프로그래밍 처럼 중간에 처리가 안된다는걸 망각했고

    많은 시간을 투자했지만 수확을 못해서 머리가 아픈 상황에서 떠올리게 되었고 재대로 된 처리를 하기 위해

    고민했습니다. 

     

    1. 아래 처럼 코드가 시작될 때 처리를 할건지 ?

    jQuery(document).ready(function () {
        LoginCheck();
        getCategories();
        getHotPartyPost()
        getNearPartyPost()
    })

    2. js 파일을 동일하게 하나 더 만들어 templates 에서 if 문을 돌려 각 상황에 맞게 적용할건지

    3. 중간에 값이 변경되지 않는다면 덮어 씌우는건 되지않을까 ? 

     

    세가지가 있었고 3번이 좋겠다는 팀원 의견을 받아 아래처럼 시도해 보았습니다.

    코드가 너무 길어져서 <<<<<< 체크함

    function get_partypost(postId) {
        $('#partypost').empty()
        $.ajax({
            type: "GET",
            url: '/api/party-posts/' + postId,
            headers: {
                "Authorization": getCookieValue('Authorization')
            },
            success: function (response) {
                const token = getCookieValue('Authorization');
                const tokenParts = token.split('.');
                const tokenPayload = JSON.parse(atob(tokenParts[1]));
                const loginUserId = tokenPayload.id;
                console.log(loginUserId)
    
                let responseData = response['data']
                console.log(response)
                let userId = responseData['userId'] //파티장Id
                let nickname = responseData['nickname']
                let title = responseData['title']
                let content = responseData['content']
                let categoryId = responseData['categoryId']
                let categoryName = responseData['categoryName']
                let status = responseData['status']
                let acceptedMember = responseData['acceptedMember'] + 1
                let maxMember = responseData['maxMember']
                let partyDate = responseData['partyDate']
                let closeDate = responseData['closeDate']
                let day = responseData['day']
                let address = responseData['address']
                let detailAddress = responseData['detailAddress']
                let partyPlace = responseData['partyPlace']
                let viewCnt = responseData['viewCnt']
                let joinMember = responseData['joinMember']
                let tempHtml = `
    
                <!-- Page Content-->
                <div id="partypost">
                    <section class="py-5">
                        <div class="container px-5 my-5">
                            <div class="row gx-5">
                                <div class="col-lg-3">
                                    <div class="d-flex align-items-center mt-lg-5 mb-4">
                                        <div class="ms-3">
                                            <div class="fw-bold">파티장 닉네임: ${nickname}</div>
                                            <button class="btn btn-warning rounded-pill" onclick="otherProfilePageClick(${userId})">유저정보
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-9">
                                    <!-- Post content-->
                                    <article>
                                        <!-- Post header-->
                                        <header class="mb-4 mt-5">
                                            <!-- Post title-->
                                            <h1 class="fw-bolder mb-1">${title}</h1>
                                            <!-- Post meta content-->
                                            <div class="fw-bold fst-italic mb-2 fs-4 text-end">마감일자 : ${closeDate}</div>
                                            <div class="text-muted fst-italic text-end">조회수: ${viewCnt}</div>
                                            <!-- Post categories-->
                                            <a class="badge bg-secondary text-decoration-none link-light">Status: ${status}</a>
                                            <a class="badge bg-secondary text-decoration-none link-light">카테고리 : ${categoryName}</a>
                                        </header>
                                        <!-- Post content-->
                                        <section>
                                            <div class="card bg-light mb-3">
                                                <div class="card-body my-2 fs-2">
                                                    ${content}
                                                </div>
                                            </div>
                                        </section>
                                        <!-- Post feature-->
                                        <section class="mb-5">
                                            <a class="badge bg-secondary text-decoration-none link-light p-sm-3 rounded-pill" onclick="clickReportPartyPost(${postId})">이 모집글 신고</a>
                                            <a class="badge bg-secondary text-decoration-none link-light p-sm-3 rounded-pill" onclick="clicklike(${postId})">좋아요</a>
                                            <p class="fs-5 mb-2 fw-bold">현재 파티원: </p>
                                            <div id="joinmember"></div>
                                            <p class="fs-5 mb-2 fw-bold">모집 인원: ${acceptedMember} / ${maxMember}</p>
                                            <p class="fs-5 mb-2 fw-bold">모임 일자: ${partyDate} + ${day} </p>
                                            <p class="fs-5 mb-2 fw-bold">주소: ${address} ${detailAddress}</p>
                                            <p class="fs-5 fw-bold">장소: ${partyPlace}</p>
                                        </section>
                                    </article>
                                    <div id="setbutton">
                                    <a class="btn-long btn-primary btn-xl-long rounded-pill" onclick="clickParticipation(${postId})">신청 (1:1 채팅)</a>
                               </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
                    `
                if (loginUserId !== userId) {
                    document.getElementById(`updatePost`).display.style.display = 'none';
                }
    
    // >>>>>>>>>>>> 해당 부분 <<<<<<<<<<<<<<<
                if (loginUserId === userId) {
                    tempHtml = `
    
                <div id="partypost">
                    <section class="py-5">
                        <div class="container px-5 my-5">
                            <div class="row gx-5">
                                <div class="col-lg-3">
                                    <div class="d-flex align-items-center mt-lg-5 mb-4">
                                        <div class="ms-3">
                                            <div class="fw-bold">파티장 닉네임: ${nickname}</div>
                                            <button class="btn btn-warning rounded-pill" onclick="otherProfilePageClick(${userId})">유저정보
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-lg-9">
                                    <!-- Post content-->
                                    <article>
                                        <!-- Post header-->
                                        <header class="mb-4 mt-5">
                                            <!-- Post title-->
                                            <h1 class="fw-bolder mb-1">${title}</h1>
                                            <!-- Post meta content-->
                                            <div class="fw-bold fst-italic mb-2 fs-4 text-end">마감일자 : ${closeDate}</div>
                                            <div class="text-muted fst-italic text-end">조회수: ${viewCnt}</div>
                                            <!-- Post categories-->
                                            <a class="badge bg-secondary text-decoration-none link-light">Status: ${status}</a>
                                            <a class="badge bg-secondary text-decoration-none link-light" href="#!">카테고리 : ${categoryId}</a>
                                        </header>
                                        <!-- Post content-->
                                        <section>
                                            <div class="card bg-light mb-3">
                                                <div class="card-body my-2 fs-2">
                                                    ${content}
                                                </div>
                                            </div>
                                        </section>
                                        <!-- Post feature-->
                                        <section class="mb-5">
                                            <a class="badge bg-secondary text-decoration-none link-light p-sm-3 rounded-pill" href="#!">이 모집글 신고</a>
                                            <a class="badge bg-secondary text-decoration-none link-light p-sm-3 rounded-pill" onclick="clicklike(${postId})">좋아요</a>
                                            <p class="fs-5 mb-2 fw-bold">현재 파티원: </p>
                                            <div id="joinmember"></div>
                                            <p class="fs-5 mb-2 fw-bold">모집 인원: ${acceptedMember} / ${maxMember}</p>
                                            <p class="fs-5 mb-2 fw-bold">모임 일자: ${partyDate} + ${day} </p>
                                            <p class="fs-5 mb-2 fw-bold">주소: ${address} ${detailAddress}</p>
                                            <p class="fs-5 fw-bold">장소: ${partyPlace}</p>
                                        </section>
                                    </article>
                                    <div id="setbutton">
                                    <a class="btn-long btn-primary btn-xl-long rounded-pill" onclick="clickUpdate(${postId})">수정하기</a>
                               </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div> `
    
                }

     

    이게 적용이 되서 놀랐습니다 제가 이해하기론 중간에 값 변경이 안되는 이유는 이미 tempHtml 이 적용이 되서 수정해도 변함이 없는거였고 위 코드는 조건문을 충족한다면 적용된 tempHtml 을 덮어 씌워서 바뀐거라고 이해했습니다

     

     

    '내일배움캠프' 카테고리의 다른 글

    88 TIL  (1) 2023.03.07
    87 TIL  (1) 2023.03.05
    85 TIL  (0) 2023.02.28
    83 TIL  (0) 2023.02.27
    82 TIL  (0) 2023.02.23
Designed by Tistory.