hamid
hamid

Reputation: 21

localStorage returns undefined when page is reloaded

I'm saving the array in localStorage but when I try to retrieve the data from it return undefined. Then I call upon the retreiveData function to display the data.

let LIST, id;

if (localStorage.getItem('todo')) {
    LIST = JSON.parse(localStorage.getItem('todo'));
    id = LIST.length;
    retreiveData(LIST);
} else {
    LIST = [];
    id = 0;
}

function retreiveData(arr) {
    arr.forEach(el => {
        addToDo(el.toDo, el.id, el.done, el.trash);
    });
}

function addToDo(toDo, id, done, trash) {

    if (trash) { return; }

    const DONE = done ? check : unCheck;

    const newHTML = `
                <li class="item">
                ${toDo} <i class="${DONE} checked" data-task="complete" id="${id}"></i>
                <i class="ion-ios-trash-outline icon" data-task="delete" id="${id}"></i>
            </li> `;

    list.insertAdjacentHTML('beforeend', newHTML);
}

document.getElementById('listBtn').addEventListener('click', event => {
    event.preventDefault();

    const toDo = input.value;

    if (toDo) {
        addToDo(toDo, id, false, false);
        LIST.push({
            name: toDo,
            id: id,
            done: false,
            trash: false

        });
    }
    localStorage.setItem('todo', JSON.stringify(LIST));

    input.value = '';
    id++;

});



function markAsDone(element) {


    element.classList.toggle(check);
    element.classList.toggle(unCheck);

    LIST[element.id].done = LIST[element.id].done ? false : true;
}

function deleteToDo(element) {
    element.parentNode.parentNode.removeChild(element.parentNode)

    LIST[element.id].trash = true;

}


list.addEventListener('click', event => {

    const element = event.target;
    const elementID = element.id;

    if (element.dataset.task == 'delete') {
        deleteToDo(element);
    } else if (element.dataset.task == 'complete') {
        markAsDone(element);
    }
    localStorage.setItem('todo', JSON.stringify(LIST));

});

Upvotes: 0

Views: 3365

Answers (1)

Ludolfyn
Ludolfyn

Reputation: 2075

Might it be that the retrieveData() function is undefined and not localStorage.todos?
Try something like this:

let list = [ { "name": "Do shopping ", "id": 0, "done": false, "trash": false }, { "name": "work on project", "id": 1, "done": false, "trash": false } ];

localStorage.todo = JSON.stringify(list);

let theData;
if (localStorage.todo) {
    theData = JSON.parse(localStorage.todo)
    console.log(theData);
} else {
    console.log('No todos');
}

OR

It might be that you're trying to use localStorage on your local machine. For security reasons it won't work. What you might need to do is run it on a local server. You can do it by following these steps.

If you have PHP installed on your computer:

  1. Open up your terminal/cmd
  2. Navigate into the folder where your website files are
  3. While in this folder, run the command php -S localhost:3000
  4. Open up your browser and in the URL bar go to localhost:3000. Your website should be running there.

or

If you have Node.js installed on your computer:

  1. Open up your terminal/cmd
  2. Navigate into the folder where your website files are
  3. While in this folder, run the command npm init -y
  4. Run npm install live-server -g or sudo npm install live-server -g on a mac
  5. Run live-server and it should automatically open up a new tab in the browser with your website open.

or

You can use XAMPP

NOTE: remember to have an index.html file in the root of your folder or else you might have some issues.

OR

It could be the browser settings.

In Chrome, when you go to settings > site settings > cookies and site data, there is an option that says Allow sites to save and read cookie data (recommended). If that is turned off then you won't be able to use localStorage either.

OR

If none of the above fixes it, then you might want to wrap the function that saves to localStorage in a try-catch block and see if an error gets returned and take it from there:

let list = [ { "name": "Do shopping ", "id": 0, "done": false, "trash": false }, { "name": "work on project", "id": 1, "done": false, "trash": false } ];

try {
  localStorage.todo = JSON.stringify(list);
} catch(error) {
  alert(error)
}

Upvotes: 2

Related Questions