React 부트캠프 15일차 TIL

정다롱·2024년 8월 4일

내일배움캠프 TIL

목록 보기
9/39

며칠 지났는지 계산하기 힘들어서 곧 날짜를 빼야겠다.

🖥️ 로컬스토리지 사용하기

⭐ 로컬스토리지란?

데이터를 서버가 아닌 클라이언트 내에 저장할 수 있게 지원해주는 저장소
새로고침, 재실행 등을 해도 데이터가 사라지지 않고 유지됨


팀 프로젝트 필수 과제에 리뷰 기능-로컬 스토리지 사용하기가 있었다. 리뷰라면 서버에 저장하고 불러오는 게 맞지만 앞으로 배울 내용 중에 로컬스토리지를 중요하게 다루는 부분이 있어 미리 사용해보라는 의미로 추가된 것 같았다. 우리 조는 즐겨찾기같은 기능을 추가하기에는 어려움이 있을 것 같아 공지대로 댓글 기능에 로컬스토리지를 사용하기로 했다.



⭕ 로컬 스토리지에 데이터 저장하기

  let user = document.getElementById("inputUser").value;
  let comment = document.getElementById("inputComment").value;
  let password = document.getElementById("inputPw").value;
  let star = document.getElementById("star").value;

우선 각 입력창(닉네임, 내용, 비밀번호, 별점)의 밸류값을 변수에 할당했다.

  function addComment(movieId, user, comment, password, star) {
    let newComment = {
      user: user,
      comment: comment,
      password: password,
      star: star,
      time: new Date().toLocaleString()
    };

입력된 데이터에 타임스탬프를 추가해 객체를 생성해주고

localStorage.setItem(`${movieId}_comment`, JSON.stringify(comments));

setItem 메소드를 사용해 로컬스토리지에 저장했다. 로컬스토리지에는 자바스크립트 객체를 바로 저장할 수 없기 때문에 JSON.stringify(comments)로 객체를 문자열로 바꾸어 저장했다.

function getComments(movieId) {
  let comments = localStorage.getItem(`${movieId}_comment`);

  if (comments) {
    return JSON.parse(comments);
  } else {
    return [];
  }
}

반대로 데이터를 꺼내올 때는 JSON.parse 를 사용해 문자열을 객체로 바꿔주어야 정상적으로 사용이 가능하다!

  comments.forEach((comment) => {
    let listItem = document.createElement("div");
    listItem.className = "commentBox";
    listItem.innerHTML = `
      <p class="commentStar" id="commentStar">${comment.star}</p>
      <p class="commentText" id="commentText">${comment.comment}</p>
    <div>
      <p class="commentUser" id="commentUser">${comment.user}</p>
      <p class="commentTime" id="commentTime">${comment.time}</p>
    </div>
      <button class="edit" id="commentEdit">수정</button>
      <button class="del" id="commentDel">삭제</button>
    `;

    commentList.appendChild(listItem);
  });

붙이는 건 자주 썼던 appendChild를 사용했다.

이제 수정 삭제 버튼을 누르면 비밀번호를 입력받고 일치하면 작동, 일치하지 않으면 비밀번호가 일치하지 않습니다 팝업 띄우는 것만 구현하면 끝난다 ... !! 야호

0개의 댓글