Skip to content Skip to sidebar Skip to footer

How To Make It So That Data Doesn't Get Lost When Refreshed In Javascript?

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:

Solution 1:

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>

Solution 2:

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


Post a Comment for "How To Make It So That Data Doesn't Get Lost When Refreshed In Javascript?"