1

I am currently building a to-do list app and I have already saved the data using the localStorage API.

The desired data, however, appears in the console whenever I console.log it but it still doesn't save in the DOM.

I also added the getItem() function and logged it into the console and I can still view it in the console, find here: getItem content in the console

But it just doesn't store in the browser

Seeing this, it is in your inclination that it should have stored in the DOM and the content still remains after reloading but that just isn't the case here.

This function below adds a new item to the list, it also deletes and crosses out completed items too:

let id = 0;
function addTaskFunc() {

    const aTask = `
    <div class="task" id="task-${id}">
        <button class="done__btn">
            <i class="far fa-check-square"></i>
        </button>
        <p>${box.value}</p>
        <button class="priority">Make priority</button>
        <button class="cancel__btn">
            <i class="far fa-times-circle"></i>
        </button>
    </div>
`;


    const x = box.value;
    if (x) {
        taskList.insertAdjacentHTML('afterbegin', aTask);
        box.value = '';
        ;

        let cid = id;

        const cancelBtn = document.querySelector(`#task-${id} .cancel__btn`);
        cancelBtn.addEventListener('click', () => {
        deleteItem(cid);
        });

        let cid2 = id;

        // code for marking out an item as done

        let cid3 = id;

        // code for appending an item to the top of DOM

        let cid4 = id;
        persistData(cid4);
        readData(cid4);
        id++;  
    }
}

newTask.addEventListener('click', addTaskFunc); // Button to activate the function

persistData = id => {
    const el = document.querySelector(`#task-${id}`);
    localStorage.setItem('addedTasks222', el.innerHTML);

};

readData = id => {
    const el = document.querySelector(`#task-${id}`);
    const saved = localStorage.getItem('addedTasks222');
    if (saved) el.innerHTML = saved;
    console.log(el.innerHTML); // This line of code appears in the console
}

I also tried doing it this way inside of the addTaskFunc:

const r = document.querySelector(`#task-${id} .task`);
r.addEventListener('load', () => {
          persistData(cid4);
          readData(cid4);
 });

When I try it with the method above I get the error code in the console: Cannot read property of addEventListener of null.

I feel there is something wrong somewhere but I just cannot seem to find out where I am missing it.

One last thing, the localStorage only seems to store only one item into the key. Do I need a loop to sort that out?

2 Answers2

0

you can store an array in the local storage like this

localStorage.setItem('array', JSON.stringify(YOURARRAY))

and then you can load that with

var restoredArray = JSON.parse(localStorage.getItem('array'));

  • Thanks a lot for your reply. So with your solution, It will save the data and still show up after refreshing? This solution seems to only save the solution into an array than solving the actual problem. – Adesanya Adeniyi Marvellous May 24 '20 at 16:28
  • Are you trying to say that the reason it isn't showing up in the DOM is because I didn't store it in an array? – Adesanya Adeniyi Marvellous May 24 '20 at 22:56
  • I was looking into your code and the problem is: you are reseting the data, with the function persistData and then store the empty data to the localStorage every time you refresh the page. You need first to read the local Storage with (readData). The persistData function you need to run only when the content is change. – João Pereira May 25 '20 at 09:26
  • Pereira, now I am having another issue, it is saying it can't set property 'innerHTML' of null. Should I create a JSFiddle so you can look into it? – Adesanya Adeniyi Marvellous May 27 '20 at 15:33
0

sorry for the time.. So I was looking in to your code, and appears that you have some problems.. 1- The first one I saw, was in the persistData() function. Accidentally you are just selecting one task to store with document.querySelector(.task); to select all you need to use document.querySelectorAll(.task), this will return you an array. Because of that you only store one task. 2- Secondly is that you are trying to store html. with .innerHtml, and the innerHtml of your (".class") is buttons and etc.. You should store values. 3- At the end, when you are trying to print the data, you do document.querySelector(.task), and as you can see its returning you undefined, that's because you haven't a .task div yet.

So How you can appropriately make your app work.

1- The first thing you need to do is creating an array variable up on your js file.

let tasks = [];

2-That array will be used to store the values of your tasks with something like this

    function addItem(){
      let value = item.value; //you need to define the item some way
      tasks.push(value);
      print() //a function to print the values;
      persistData() // store the array
    }

3-To print the tasks

    function print(){
      tasks.forEach(task => {
       let div = document.createElement("div");
       div.innerHTML = `copy your html task to here, use ${task} to print the task value`
      })
    }

4-Store the tasks

function persistData(){
   localStorage.setItem('addedTasks', tasks); //store the array
};

function readData(){
   if (typeof(Storage) !== "undefined") { //check if the browser has localStorage 
    tasks = localStorage.getItem('addedTasks'); //update your array
    print();
   } else {
    //No Web Storage message
   }
};

5- Just run readData() when you load your document with

 document.addEventListener("DOMContentLoaded", function(event) {
      readData();
  });

I hope that I can help