Trying to build a simple to-do app. I have a question about storing values

Hello. I am trying to build a simple to-do app. Here is my code.

var todos = [];

console.log(todos);

function addItem() {
    
    var item = document.getElementById("item").value;
    
    todos.push(item);
    
    localStorage.setItem("todos", JSON.stringify(todos));
}

Basically, what this code does it pushes the value to an array and then it’s pushed to local storage. My problem is that every time the value is pushed, the function reloads and if you add a new item, it pushes a new value, thus rewriting the old. How I should refactor the code, so it updates the array, not overwrites it? What I am missing here? Thanks for help.

Sounds like you are pushing to local storage, but you are forgetting to retrieve from local storage and initialize todo to that value (if it exists).

1 Like

My logic was like to push and see it it gets values. It does. I can see key: value: pair. The problem is that, I would like to push, so that array grows with new values. At the moment it pushes one value and for the next value it rewrites it, so it’s always an array with one value, I need array with all the values I inputted before. I will take a break and think more about this. Breaks help. Talk with others too. Thanks for a comment!

you can get the whole array and push the locally updated array to storage.

1 Like

When you write to local storage, you are doing an assignment. In order to add something to the current stored value, you need to retrieve it and do the manipulations within your code.

1 Like

I guess I gave up easily and just looked for solutions as I am not at that level yet. I found this link: https://stackoverflow.com/questions/19635077/adding-objects-to-array-in-localstorage already made credit to this guy in my comments, but here is a code after I did a little tweaking.

function addItem() {

    var existingEntries = JSON.parse(localStorage.getItem("todos"));
    
    // Null value here if the item is not existent in localStorage

    if (existingEntries == null) {
        
        // If null, creates an empty array

        existingEntries = [];
    }

    // Selects a value from an input 

    var item = document.getElementById("item").value;

    // Pushes input value to Array
    
    existingEntries.push(item);    

    localStorage.setItem("todos", JSON.stringify(existingEntries));


}

So basically the first line tries to get “todos” from localStorage if is not existent, it creates an array. After that, the script selects the value from ‘item’ and pushes it to existing array via push method. Then array itself is pushed to localStorage. I hope I understood it correctly. I will focus now on returning the list to the page. Thanks for help guys!