Notice
Recent Posts
Recent Comments
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
관리 메뉴

SYDev

[Express] 17. Display Comment Fetch 본문

대딩코딩/웹개발 스터디

[Express] 17. Display Comment Fetch

시데브 2023. 12. 4. 17:11

Fetch 형태로 받은 comment를 바로 화면에 Display

 

comment.js 파일의 displayComment 함수를 구현

 

 파일명: comment.js

const onCreateComment = async (topic_id) => {
    const username = document.getElementById('comment-username').value;
    const content = document.getElementById('comment-content').value;

    const url = `/comment/create/${topic_id}`;
    const res = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({username: username, content: content})
    });

    if(res.ok) {
        const result = await res.json();
        console.log(result);
        displayComment(username, content);   //새로고침 없이 comment를 화면에 갱신
    }
}

/*
<div class="comment-div">
    <div>
            <p><b><%= comment.username %></b></p>
            <p><%= comment.content %></p>
    </div>
    <form action="/comment/delete/<%= comment.comment_id %>" method="post">
        <button>Delete</button>
    </form>
</div>
*/

const displayComment = (username, content) => {
    const commentContainer = document.createElement('div');
    commentContainer.className = 'comment-div';
    const commentContent = document.createElement('div');

    const usernameP = document.createElement('p');
    usernameP.innerHTML = `<b>${username}</b>`;

    const contentP = document.createElement('p');
    contentP.innerText = content;

    commentContent.appendChild(usernameP);
    commentContent.appendChild(contentP);

    const deleteBtn = document.createElement('button');
    deleteBtn.innerText = 'Delete';

    commentContainer.appendChild(commentContent);
    commentContainer.appendChild(deleteBtn);

    //실제 화면에 반영
    const commentWrapper = document.querySelector('.comment-container');
    commentWrapper.appendChild(commentContainer);
}

 

 

delete 버튼의 style 변경을 위해 input.css 파일에 align-items = start 문장을 추가

 

 파일명: input.css

.input-text,
.input-textarea {
    display: block;
    margin: 1rem;
}

.comment-div {
    margin: 1rem;
    padding: 1rem 3rem;
    border: 2px solid gray;
    border-radius: 3rem;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: start;
}