1 사용법 연습
// setItem: localstorage 정보를 저장할때 사용하는 메소드
localStorage.setItem("name", "yujeong");
localStorage.setItem("age", 100);
// getItem: localStorage에서 정보를 가져올때 사용
const result = localStorage.getItem("age");
console.log(result);
console.log(typeof result);
//local storage에 제대로 저장되지 않음
//const travel = {
//destinations: ["paris", "sydney", "taipei"],
//days: 100,
//mate: undefined,
//isAvailable: true,
//};
//localStorage.setItem("travel",travel);
// JSON.stringify/.parse 객체는 문자열로 변환해야 함
const travel = {
destinations: ["paris", "sydney", "taipei"],
days: 100,
mate: undefined,
isAvailable: true,
};
localStorage.setItem("travel", JSON.stringify(travel));
//const data = localStorage.getItem("travel");
//console.log(data.destinations);
const data = JSON.parse(localStorage.getItem("travel"));
// 콘솔에 객체 형식으로 출력됨
// console.log(data);
console.log(data.destinations);
localStorage.removeItem("name");
localStorage.clear();
2 활용 | 유튜브 댓글달기
$commentForm.addEventListener('submit', handleSumbit);
const comments = [];
function saveItem() {
localStorage.setItem("comments", JSON.stringify(comments));
}
function displayHistory () {
const savedComments = JSON.parse(localStorage.getItem('comments'));
savedComments.map(comment => {
const newCommentItem = commentItemTemplate(comment);
comments.push(comment);
$commentList.insertAdjacentHTML('afterbegin', newCommentItem);
})
}
//console.log(savedComments[0]);
displayHistory();
function handleSumbit(event){
event.preventDefault();
//console.log($commentInput.value);
const newComment = $commentInput.value;
if (!newComment) {return};
const newCommentItem = commentItemTemplate(newComment);
$commentList.insertAdjacentHTML('afterbegin', newCommentItem);
$commentInput.value = "";
comments.push(newComment);
//console.log(comments);
saveItem();
}