UMC_WEB_내부 저장소 local Stroage란??

Falco·2022년 4월 20일
0

UMC2기_WEB

목록 보기
6/9
post-thumbnail

Web 6주차 워크북

핵심 키워드

  • local Storage

local Storage는 문자열 형태로만 저장 가능

localStorage.setItem('name',"해찬");
localStorage.setItem('age',"18");

getItem : 로컬스토리지에서 아이템 가져올 때 사용

const result = localStorage.getItem('age');
console.log(result);

const travle = {
  destinations : ['파리','일본','대만'],
  days : 100,
  mate : undefined,
  isAvailable : true
}

//오브젝트는 String으로 저장 불가.
localStorage.setItem('travel',travle);
//그래서 Json으로 변환시켜 사용
localStorage.setItem('travel',JSON.stringify(travle));

//가져올 때는?
const data = localStorage.getItem('travel');
console.log(data);

//결과 :
"{'destinations':['파리','일본','대만'],'days':100,'isAvailable':true}"
//그래서 가져올 때 JSON으로 형변환
const data = JSON.parse(localStorage.getItem('travel'));
console.log(data);

//삭제
localStorage.removeItem("name");
localStorage.clear();
  • Session Storage

  • JSON 이란
    JavaScript Object Notation라는 의미의 축약어로 데이터를 저장하거나 전송할 때 많이 사용되는 경량의 DATA 교환 형식

  • Local Storage와 Session Storage의 차이
    sessionStorage는 현재 떠 있는 탭 내에서만 유지된다.
    그러나 제공하는 프로퍼티와 메서드는 같다.
    다른 탭에서 현재 페이지를 오픈하면 리셋됨
    LocalStorage와 SessionStorage

  • 만약 사용자의 이름등 개인정보는 local과 session 둘 중 어디에 담아야할까?
    local에 담아야지 다음에 다른 탭에서 열었을 때도 사용가능 -> 이왕이면 서버에 저장?


+) 2개이상의 창에서 storage이벤트가 실행되었을 때 사용할 수 있는 방법

localStorage나 sessionStorage의 데이터가 갱신될 때, storage 이벤트가 실행됩니다. storage 이벤트는 다음과 같은 프로퍼티를 지원합니다.

  • key – 변경된 데이터의 키(.clear()를 호출했다면 null)
  • oldValue – 이전 값(키가 새롭게 추가되었다면 null)
  • newValue – 새로운 값(키가 삭제되었다면 null)
  • url – 갱신이 일어난 문서의 url
  • storageArea – 갱신이 일어난 localStorage나 sessionStorage 객체

논의해보면 좋은 것들

  • Local Storage와 Session Storage의 차이에 대해 알아보기
  • Local Storage가 사용되는 기능에 대해 리스트업 해보기
    쿠키 및 캐쉬 검색기록
    유투브 : 볼륨, 최근 탭, 최근 재생어디까지했는지 등등..

실습

const comments = [];

댓글을 담을 변수인 comments를 생성
페이지를 새로고침하거나 열때마다 comments가 새로 생성되서 굳이 let으로 생성할 필요가 없는 듯


$commentForm.addEventListener("submit",handleSubmit);

function handleSubmit(e){
    e.preventDefault();
    const newComment = $commentInput.value;
    if (!newComment){
        return;
    }
    const newCommentItem = commentItemTemplate("이해찬",newComment,"https://yt3.ggpht.com/yti/APfAmoFjoi5B8bE0j5805xHwq1nnfHaRErC54Tcwrre3=s88-c-k-c0x00ffffff-no-rj-mo");
    $commentList.insertAdjacentHTML("afterbegin",newCommentItem);
    $commentInput.value = "";
	
    //(submit)이벤트가 발생되면 comments에 댓글담기
    comments.push(newComment);
    saveItem();
}

function saveItem(){
   //배열도 JSON으로 변환해서 저장해야지 인덱스로 받아올 수 있음
   localStorage.setItem('comments',JSON.stringify(comments));
}

로컬스토리지에 있는 댓글 정보 받아와서 화면에 뛰워주기
map사용법 MDN

function displayHistory() {
    const savedComments = JSON.parse(localStorage.getItem('comments'));
    savedComments.map(arrcomments => {
        const newCommentItem = commentItemTemplate("이해찬",arrcomments,"https://yt3.ggpht.com/yti/APfAmoFjoi5B8bE0j5805xHwq1nnfHaRErC54Tcwrre3=s88-c-k-c0x00ffffff-no-rj-mo");
        comments.push(arrcomments);
        $commentList.insertAdjacentHTML("afterbegin",newCommentItem);
    })
}
displayHistory();

글자 짤려도 2줄 유지하는 방법

// line-height를 max-height의 2배로 놓으면 해결
.vedioTitle{
    margin: 0 0 4px 0;
    font-family: "Roboto","Arial",sans-serif;
    font-size: 1.4rem;
    line-height: 2rem;
    max-height: 4rem;

    font-weight: 500;
    overflow: hidden;
    color: white;
}

// 1줄로 처리하는 방법
.metaText{
    font-size: 1.2rem;
    color: #AAAAAA;
    font-family: "Roboto","Arial",sans-serif;

    line-height: 1.5rem;
    max-height: 1.5rem;
    overflow: hidden;
    /* -webkit-line-clamp: 1 */
}
.extraMeta{
    line-height: 1.5rem;
    max-height: 1.5rem;
    overflow: hidden;
    /*  보여줄 줄 갯수 크롬, 사파리 제공 */
    /* -webkit-line-clamp: 1 */
}
profile
강단있는 개발자가 되기위하여

0개의 댓글