[Week 3] To-do-list Local Storage

ShiHoon Yoon·2020년 7월 31일
0

지난주에 만들었던 to-do-list 프로젝트를 매일하조 팀원 상호님 조언으로 새고로침을해도 저장이 될 수 있게 저장 기능을 추가했다.

localStorage.getItem & JSON.parse

function getDataArray () {
if (localStorage.getItem('data')) {
return JSON.parse(localStorage.getItem('data'));
} else {
return [];
}
}

localStorage.getItem의 기능
  • 키에 해당하는 값 불러오기
JSON.parse의 기능

STRING--> Javascript Object으로 변환
추가적인 설명은 이전 velog 글 확인

localStorage.setItem & JSON.stringify

function saveData(taskValue, priorityValue, deadlineValue) {
var toDoData = getDataArray();
var dataStructure = {task: taskValue, priority: priorityValue, deadline: deadlineValue};
toDoData.push(dataStructure);
localStorage.setItem('data', JSON.stringify(toDoData) );

localStorage.setItem의 기능
  • 키, 값 쌍을 보관
JSON.stringify 기능

Javascript Object--> String으로 변환
추가적인 설명은 이전 velog 글 확인

getItem,setItem 설명

function initialize(){
var toDoData = getDataArray();
if (toDoData.length > 0) {
for (var i=0; i<toDoData.length; i++){
var rowData = toDoData[i]
var rowTask = rowData.task
var rowPriority = rowData.priority
var rowDeadline = rowData.deadline
displayTask(rowTask, rowPriority, rowDeadline);
}
}
}

Obstacles

1. 원하지 않은 Alert 기능

Problem

처음에 task를 추가했을 때만 alert 기능이 뜨기를 원했다. 하지만 local storage에 저장된 값을 새로고침으로 불렀을 때도 alert가 떴다.

Solution

displayTask 함수에 shouldAlert이라는 parameters를 넣어서 if statement을 만들었다. fnTask (버튼 함수)를 눌렀을 때 displayTask함수에는 shouldAlert/true로하여 추가될 때는 alert이 뜨도록했다. 하지만 fnTask 함수의 saveData 함수부분에서는 shouldAlert input이 없어서 저장이 안 되게 했다. 그리하여 새로고침할 때는 alert이 뜨지 않았다.

function displayTask(taskValue, priorityValue, deadlineValue, shouldAlert) {
var numberOfRows = document.getElementsByTagName("tr").length;
console.log("currently there are " + numberOfRows + " number of rows");
// var remove = "Delete";
// Creating button and adding properties we want --> text, onclick
var removeButton = document.createElement("button");
removeButton.innerHTML="Delete";
console.log("I created a button when onclick will remove row at the ", numberOfRows);
removeButton.onclick= function() {
console.log("I will remove row at ", numberOfRows, " because I was clicked");
removeSelectedRow(numberOfRows);
}
if (shouldAlert) {
alert("Task added : " + taskValue);

2. Row(행) 추가 실패

Problem

새로고침을 눌렀는데 insertRow가 행을 추가할 수 없다고 했다. 새로고침을 통해 row가 추가 됐는데 새로고쳐지면서 대입할 행이 아직 만들어지지 않았기 때문이었다.

Solution

html파일에 javascript를 불러오는 위치를 line6에서 line32로 이동했다. 컴퓨터는 순서대로 읽기 때문에 이렇게 하니 테이블이 먼저 만들어진 후 local storage에서 저장된 값들을 오류 없이 불러왔다.

profile
Entrepreneurs Should Learn to Code

5개의 댓글

comment-user-thumbnail
2020년 7월 31일

저 복귀했습니다 ㅋㅋㅋㅋ 후 저도 얼른 JS 진도 다 빼고 to-do list 만들어야겠어요 ㅠㅠㅠ

1개의 답글
comment-user-thumbnail
2020년 8월 1일

오오 수고하셨어요!! 근데 저 버그 발견했어요!ㅋㅋ 할 일 목록 3개 만들고 밑에서부터 delete 하면 다 지워지는데 위에서부터 delete 하면 마지막 하나가 안지워지네요?! console창 한번 확인해보시면 좋을 것 같습니다!

답글 달기
comment-user-thumbnail
2020년 8월 1일

그리고 delete를 해도 새로고침하면 이게 반영이 안되어 있네요!
화면에 출력되는 할 일 목록이랑 localStorage에 저장되는 할 일 목록 데이터를 따로 구분하고 거기에 각각 id 값을 부여해서 delete를 눌렀을 때의 두 데이터 간 id 값을 비교해서 화면에 출력되는 방식을 쓰면 해결하실 수 있을 것 같아요! (저도 노마드코더에서 배운 내용입니다😅)

1개의 답글