Локальное хранилище не обновляется правильно? - PullRequest
0 голосов
/ 19 июня 2020

Я создаю приложение со списком дел, и у меня проблемы с локальным хранилищем. Todos можно «завершить» и «выбросить». Следовательно, функции completeToDo и remove todo.

Моя проблема в том, что я создаю задачу «завершить» и обновляю sh страницу, которая возвращается к незавершенной. Если я сделаю то же самое снова, это наконец сработает. Кажется, я не могу найти проблему в своем коде. Я обновляю локальное хранилище через эту строку

localStorage.setItem("TODO", JSON.stringify(LIST));

Код:

// Selecting elements
const clear = document.querySelector(".clear");
const dateElement = document.getElementById("date");
const list = document.getElementById("list");
const input = document.getElementById("input");
const plus = document.querySelector(".add-to-do");


// Classes names in css
const CHECK = "fa-check-circle";
const UNCHECK = "fa-circle-thin";
const LINE_THROUGH = "lineThrough";

// Variables
let LIST, id;

// get item from local storage

let data = localStorage.getItem("TODO");

if(data) {
    LIST = JSON.parse(data);
    id = LIST.length; // set the id to the last one in the list
    loadList(LIST); // load the list to the user interface
} else{
    // if data isnt empty
    LIST = [];
    id = 0;

}

// load items to the ui

function loadList(array){
    // loop over array
    array.forEach(function(item) {
        addToDo(item.name, item.id, item.done, item.trash);

    });
}

clear.addEventListener('click', function() {
    localStorage.clear();
    location.reload();

});


// Show todays date
const options = {weekday : "long", month:"short", day:"numeric"};
const today = new Date();
dateElement.innerHTML = today.toLocaleDateString("en-UK", options);

function addToDo(toDo, id, done, trash) {

    if(trash){ return; }
    const DONE = done ? CHECK : UNCHECK;
    const LINE = done ? LINE_THROUGH: "";

    // Adding html element to UI
    const item = `<li class="item">
                    <i class="fa ${DONE} co" job="complete" id="${id}"></i>
                    <p class="text ${LINE}">${toDo}</p>
                    <i class = "fa fa-trash-o de" job="delete" id="${id}"></i>
                  </li>`;

    // Adds todo to the end of the list
    const position = "beforeend";
    list.insertAdjacentHTML(position, item);


}

// add an item
document.addEventListener("keyup", function(even) {
    if(event.keyCode == 13){
        const toDo = input.value;

        if(toDo){
            addToDo(toDo);

            LIST.push({
                name: toDo,
                id: id,
                done : false,
                trash: false
            });

            // add item to local storage
            localStorage.setItem("TODO", JSON.stringify(LIST));
            id++;

        }
        input.value = "";
    }
});



// Complete todo

function completeToDo(element) { 

    // Updating ui
    element.classList.toggle(CHECK); // If the check is in the class list remove it or if it isnt add it to the classlist
    element.classList.toggle(UNCHECK);
    element.parentNode.querySelector(".text").classList.toggle(LINE_THROUGH);

    // Updating list

    /*
    Access the propety 'done' from the element with the selected id
    If its false change it to true if its true change it to false


    */
    LIST[element.id].done = LIST[element.id].done ? false : true;

}

function removeToDo(element) {
    // Remove from UI
    element.parentNode.parentNode.removeChild(element.parentNode);
    LIST[element.id].trash = true;


}





/*

-----------------------------HERE------------------------

*/


list.addEventListener('click', function(event) {
    const element = event.target; // return the clicked element inside the list
    const elementJob = element.attributes.job.value; // return complete or delete

    if (elementJob == "complete") {
        completeToDo(element); // if the user clicks the complete button it calls the complete function
    } else if (elementJob == "delete") {
        removeToDo(element); // if the user clicks the trash icon it removes it
    }

    // Local storage is updated here
    localStorage.setItem("TODO", JSON.stringify(LIST));

});

Поэтому я обновляю локальное хранилище, когда происходит одно из этих двух событий

TL; DR Если я создаю задачу, завершите ее, затем нажмите refre sh она вернется обратно к незавершенной, требуются попытки нажать кнопку «Завершить», чтобы сохранить ее

...