My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

localStorage returning undefined

Marvellous Adesanya's photo
Marvellous Adesanya
·May 23, 2020

I am currently building a to-do list app and I want to save the added items to the localStorage so they can appear when reloaded.

I added the localStorage API, being a beginner to programming I am still a little confused on how to add the localStorage to my function. The key of the localStorage is saved but the value is returning undefined.

This code block is to add a new item to the to-do list which works perfectly fine:

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) {
        const adTask = taskList.insertAdjacentHTML('afterbegin', aTask);
        box.value = '';

}

The event handler for adding a new item is as follows:

newTask.addEventListener('click', addTaskFunc);

Now after adding a new item to the list, I am trying to save it to localStorage. I saved the result of this method: taskList.insertAdjacentHTML('afterbegin', aTask); into this variable: const adTask

and then added the localStorage API into the addTaskFunc function block. Here is the code for the localStorage:


     let id = 0;
     function addTaskFunc() {

    // InsertAdjacentHTML code

    const x = box.value;
    if (x) {
        const adTask = taskList.insertAdjacentHTML('afterbegin', aTask);
        box.value = '';
        localStorage.setItem("addedTask2", adTask); //Code to save data returning undefined in console
     }

Where am I getting it wrong?