본문 바로가기

Front End/Javascript

[JavaScript] localforage를 이용한 CRUD(저장/읽기/수정/삭제)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>localforage CRUD(Create, Read,Uodate,Delete)</title>
    <script>
        // 내용이 저장될 변수
        let comments = [];
        // 내용이 없을 경우 저장될 초기 데이터
        let initialComments = [
            { id: 1, comment: '출첵 입니다. 와 일빠다....' },
        ]

        // DOM을 모두 읽고 실행
        window.onload = () => {
            // 취소하기 버튼을 숨긴다.
            document.querySelector("#resetBtn").style.display = 'none';
            // 로컬 저장소에서 데이터 읽기
            localforage.ready(function () {
                localforage.getItem('comments', (status, data) => {
                    comments = data;
                    // 데이터가 없다면
                    if (comments == null || comments.length == 0) {
                        // 로컬저장소에 데이터를 저장하고
                        localforage.setItem('comments', initialComments, () => {
                            localforage.getItem('comments', (status, data) => {
                                comments = data;
                                console.log(JSON.stringify(comments));
                                // 화면에 데이터 출력
                                viewComments();
                            });
                        });
                    }else{
                        // 화면에 데이터 출력
                        viewComments();
                    }
                });
            });
        }

        // 화면에 데이터를 출력해 주는 함수
        function viewComments() {
            let result = "";
            comments.forEach((comment) => {
                result += `${comment.id}. ${comment.comment}`;
                result += `  <button onclick="editForm(${comment.id},'${comment.comment}')">수정</button>`;
                result += `  <button onclick="removeComment(${comment.id})">삭제</button><br/>`;
            });
            document.querySelector("#comments").innerHTML = result;
        }

        // 데이터 중에서 제일큰 id를 읽어와 +1을 해서 다음 아이디를 만들어 주는 함수
        function getNextID() {
            return comments.length == 0 ? 1 : Math.max(...comments.map(({ id }) => id)) + 1;
        }

        // 수정 버튼을 눌렀을때 처리할 함구
        function editForm(id, comment) {
            document.querySelector("#id").value = id; // id표시
            document.querySelector("#comment").value = comment; // comment 표시
            // 버튼제목을 수정하기로
            document.querySelector("#btn").innerText = '수정하기'
            // 취소하기 버튼 보이기
            document.querySelector("#resetBtn").style.display = 'inline';
        }

        // 수정하기 버튼 눌렀을때 실제 수정하는 함수
        function editComment() {
            // 값읽기
            let id = document.querySelector("#id").value;
            let comment = document.querySelector("#comment").value;
            // 값이 있으면
            if (comment != null && comment.trim().length > 0) {
                // 반복하면서 같은 id를 찾아 comment를 수정
                comments.forEach((item) => {
                    if (item.id == id) {
                        item.comment = comment;
                    }
                });
                // 데이터 갱신 및 화면 다시 그리기
                update();
                // 폼을 원래대로 돌리기
                resetComment();
            }
        }
        // 지정 id의 comment를 삭제해 주는 함수
        function removeComment(id) {
            console.log(...comments.filter((comment) => comment.id != id));
            // 내용중 id가 다른것만 복사
            comments = [...comments.filter((comment) => comment.id != id)];
            // 데이터 갱신 및 화면 다시 그리기
            update();
        }
        // 저장해주는 함수
        function saveComment() {
            let id = getNextID(); // id만들기
            // 입력값 읽기
            let comment = document.querySelector("#comment").value;
            // 입력 데이터가 있으면
            if (comment != null && comment.trim().length > 0) {
                // 객체 작성
                let obj = { "id": id, "comment": comment };
                console.log(JSON.stringify(obj));
                // 배열에 추가
                comments.push(obj);
                // 입력필드 지우기
                document.querySelector("#comment").value = "";
                // 데이터 갱신 및 화면 다시 그리기
                update();
            }
        }

        function update() {
            // 로컬저장소에 데이터를 저장하고
            localforage.setItem('comments', comments, () => {
                // 로컬저장소에 데이터를 읽고
                localforage.getItem('comments', (status, data) => {
                    comments = data;
                    // 화면에 표시
                    viewComments();
                });
            });
        }

        // 폼을 원래대로 만들어 주는 함수
        function resetComment() {
            document.querySelector("#id").value = 0;
            document.querySelector("#comment").value = '';
            document.querySelector("#btn").innerText = '저장하기'
            document.querySelector("#resetBtn").style.display = 'none';
        }

        // 버튼의 제목에따라 저장/수정을 해주는 함수
        function updateComment() {
            let button = document.querySelector("#btn").innerText;
            console.log(button);
            switch (button) {
                case '저장하기':
                    saveComment();
                    break;
                case '수정하기':
                    editComment();
                    break;
            }
        }
    </script>
</head>

<body>
    <input type="hidden" id="id" value="0" />
    <input type="text" id="comment" placeholder="저장할 내용을 입력하세요" />
    <button onclick="updateComment()" id="btn">저장하기</button>
    <button onclick="resetComment()" id="resetBtn">취소하기</button>
    <hr>
    <div id="comments"></div>
</body>

</html>