Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

JavaScript
let id = 0;
    function addTaskFunc() {
        
        const aTask = `
        <div class="task" id="task-${id}">
            <button class="done__btn">
                
            </button>
            <p>${box.value}</p>
            <button class="priority">Make priority</button>
            <button class="cancel__btn">
                ^__i class="far fa-times-circle">
            </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: `
JavaScript
const adTask
`

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

JavaScript
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?

What I have tried:

As earlier stated, I saved the insertAdjacentHTML method in a constant and then called the const in the localStorage but it returns undefined.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900