Kevin Powell - CommunityKP-C
Kevin Powell - Community15mo ago
16 replies
Faker

How to prevent an array storing items from local storage from initializing each time

Hello guys, sorry to disturb you all; I'm working on a to-do list small project; I was able to add items to the localStorage and retrieve them when web page loads but the problem is each time the page loads, the array is emptied, it's re-intialized and I lost my previous saves.

Have a look at my codepen:

https://codepen.io/Fakeur/pen/OJKwvor

Here is my JS code:

const input = document.querySelector('#task_list');
const btn = document.querySelector('.add');
const items = document.querySelector('.items');
let array_of_items = [];

btn.addEventListener('click', () => {
    if (input.value !== '') {
        let list_item = document.createElement('li');
        list_item.textContent = input.value;
        items.appendChild(list_item);
        array_of_items.push(list_item.textContent);
        console.log(array_of_items);
        localStorage.setItem('Tasks', JSON.stringify(array_of_items));
        input.value = '';
    }
})


function retrieveTasks () {
    if (array_of_items.length > 0) {
        for (let i = 0; i < retrieved_tasks.length; i++) {
            let list_item = document.createElement('li');
            list_item.textContent = retrieved_tasks[i];
            items.appendChild(list_item);
        }
    }
}

window.onload = retrieveTasks;


// The problem with this code is that the array is initialises to an empty array each time, I only overwriting previous tasks
Was this page helpful?