0

I am making a to do list, and to do items are being lost (as expected) when page is refreshed. How do I stop it from clearing the items when the page is refreshed???????

Html:

        <div class="row">
                <input id="userInput" type="text" placeholder="New item..." maxlength="190"autofocus>
                <button id="enter">Add</button>
        </div>

        <div class="row" id="items">
            <div class="listItems col-12">
                <ul class="col-12 offset-0 col-sm-8 offset-sm-2">
                </ul>
            </div>
        </div>      
    </div>

JS:

    function createListElement() {
        var li = document.createElement("li"); 
        li.appendChild(document.createTextNode(input.value));
        ul.appendChild(li);
        function crossOut() {
            li.classList.toggle("done");
        }
        li.addEventListener("click",crossOut);

        var dBtn = document.createElement("button");
        dBtn.appendChild(document.createTextNode("X"));
        li.appendChild(dBtn);
        dBtn.addEventListener("click", deleteListItem);

        function deleteListItem(){
            li.classList.add("delete");
        }
}

    //enter works
    function addListAfterKeypress(event) {
        if (inputLength() > 0 && event.which ===13) { 
            createListElement();
        } 
    }

    input.addEventListener("keypress", addListAfterKeypress);
  • Why don't you try storing those values in a database? – Ankit Beniwal May 30 '20 at 04:29
  • JavaScript memory will be flushed when you refresh the page, period. However, the [Web Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API) provides you a means of persisting data in browser storage. Please note that this comes with certain caveats and security tradeoffs. – Alexander Nied May 30 '20 at 04:29
  • You can use in this case the localStorage or sessionStorage web storage api. – Beller May 30 '20 at 04:29
  • 1
    Marking this as a duplicate of [this post](https://stackoverflow.com/questions/16206322/how-to-get-js-variable-to-retain-value-after-page-refresh), which is in turn marked as a duplicate of [this post](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads). – Alexander Nied May 30 '20 at 04:31

2 Answers2

0

You can't get your tasks if you refreshed the page without storing them somewhere,

so I recommend you to use local storage as a starting for you

the whole idea here is when you press enter to submit a task you need to make an array to push each task and at the same time update your local storage with that array

and then you need to make an event listener ('DOMContentLoaded') so if you refresh your page then you retrieve tasks from local storage and append them to dom

I hope this answer clarify your issue

// select elements
const input = document.getElementById('userInput');
const ul = document.querySelector('ul');

function createListElement() {
    var li = document.createElement("li");
    li.appendChild(document.createTextNode(input.value));
    ul.appendChild(li);

    // update array with storage
    let arr = getTasks();
    // push li text to array
    arr.push(li.textContent);
    // update localStorage
    localStorage.setItem('tasks', JSON.stringify(arr));

    function crossOut() {
        li.classList.toggle("done");
    }
    li.addEventListener("click", crossOut);

    var dBtn = document.createElement("button");
    dBtn.appendChild(document.createTextNode("X"));
    li.appendChild(dBtn);
    dBtn.addEventListener("click", deleteListItem);

    function deleteListItem() {
        li.classList.add("delete");
    }
}

//enter works
function addListAfterKeypress(event) {
    if (input.value.length > 0 && event.which === 13) {
        createListElement();
        // wipe out input
        input.value = '';
    }
}

input.addEventListener("keypress", addListAfterKeypress);

// check localStorage
function getTasks() {
    let tasks;
    if (localStorage.getItem('tasks') === null) {
        tasks = [];
    } else {
        tasks = JSON.parse(localStorage.getItem('tasks'));
    }
    return tasks;
}

// on dom loading append tasks
window.addEventListener('DOMContentLoaded', () => {
    // get tasks from storage
    let arr = getTasks();

    // loop through tasks
    let foo = '';
    arr.forEach(item => {
        foo += `
                    <li>${item}<button>X</button></li>
                    `;
    });

    // append tasks to dom
    ul.innerHTML = foo;

});
    <div class="row">
        <input id="userInput" type="text" placeholder="New item..." maxlength="190" autofocus>
        <button id="enter">Add</button>
    </div>

    <div class="row" id="items">
        <div class="listItems col-12">
            <ul class="col-12 offset-0 col-sm-8 offset-sm-2">
            </ul>
        </div>
    </div>
    </div>
Eissa Saber
  • 161
  • 1
  • 8
  • But i have another problem now, I can only delete the tasks that are from current session, but not from before refreshing. So if i make a task and refresh, I cannot delete it. Do you know why it is happening? –  May 30 '20 at 14:29
  • @CodingLieutenant47 - glad to hear this answer worked for you; please mark this answer as correct to both give this user credit and provide guidance to other visitors to this question. If you are having a new, separate issue, you may consider opening that as a new question rather than trying to resolve it in the comments of the correct answer. Good luck, and happy coding! – Alexander Nied May 30 '20 at 20:19
  • because you should delete tasks from local storage as well as you delete them from UI, in this case, you have to trigger which task has been deleted from UI based on unique ID and then loop through tasks in local storage to splice out that task and then update the localstorage – Eissa Saber May 31 '20 at 15:21
0

It depends on the use case, if it's something like managing date centrally you need to go with database. if it is some minor data user specific you can go with local storage.

To use localStorage in your web applications, there are five methods to choose from:

setItem(): Add key and value to localStorage
getItem(): Retrieve a value by the key from localStorage
removeItem(): Remove an item by key from localStorage
clear(): Clear all localStorage
key(): Passed a number to retrieve nth key of a localStorage

setItem()

window.localStorage.setItem('name', 'Obaseki Nosa');

const person = {
    name: "Obaseki Nosa",
    location: "Lagos",
}
window.localStorage.setItem('user', JSON.stringify(person));

getItem()

window.localStorage.getItem('user');

JSON.parse(window.localStorage.getItem('user'));

removeItem()

window.localStorage.removeItem('name');

clear()

window.localStorage.clear();

Note: localStorage is synchronous, with no data protection and limited to 5MB across all major browsers

Ravi
  • 91
  • 1
  • 8