skip to Main Content

(Edited) I’m fairly new to JS and I’m trying to figure out why I can’t save these Created Elements into localStorage. What I’ve tried to do is localStorage.setItem("data", incomeContainer.innerHTML) which from what I understand, should update and save the innerHTMl of incomeContainer every time something changes within it but I can’t seem to save the input values when someone adds something. Could anyone help me understand why that is and how I should go about it? I’ve cut out most of the code to keep it as simple as possible.

let incomeContainer = document.querySelector('#inc');



function userInput() {
addInfo.forEach(btn => {
    btn.addEventListener('click', (e) => {
        let data = e.currentTarget.dataset.add;

        if (data === "income") {
            addIncome();
            netWorth();
        };
       
    })
})

}

function addIncome() {
        if (incomeName.value !== "" && incomeAmount.value !== "") {
        let trackedDiv = document.createElement('div');
        let inputName = document.createElement('input');
        let inputAmount = document.createElement('input');
        let btnDiv = document.createElement('div');
        let editBtn = document.createElement('button');
        let checkBtn = document.createElement('button');
        let deleteBtn = document.createElement('button');

    trackedDiv.classList.add('tracked');
    inputName.classList.add('track_name');
    inputName.type = "text";
    inputAmount.classList.add('track_amount');
    inputAmount.type = "number";
    btnDiv.classList.add('btn_div');
    editBtn.classList.add('edit_item');
    checkBtn.classList.add('check_item');
    deleteBtn.classList.add('delete_item');


    editBtn.innerHTML = `<i class="fa-solid fa-pen-to-square"></i>`;
    checkBtn.innerHTML = `<i class="fa-solid fa-check"></i>`;
    deleteBtn.innerHTML = `<i class="fa-solid fa-trash"></i>`;


    inputName.disabled = "disabled";
    inputAmount.disabled = "disabled";



    inputName.value = incomeName.value;
    inputAmount.value = incomeAmount.value;

    incCounter += parseFloat(inputAmount.value);


    let convertedIncome = new Intl.NumberFormat('en-US', {style: "currency", currency: "USD", minimumFractionDigits: 0, maximumFractionDigits: 2}).format(incCounter);

    incomeTotal.innerText = convertedIncome;


    trackedDiv.appendChild(inputName);
    trackedDiv.appendChild(inputAmount);
    btnDiv.appendChild(editBtn);
    btnDiv.appendChild(checkBtn);
    btnDiv.appendChild(deleteBtn);
    trackedDiv.appendChild(btnDiv);
    incomeContainer.appendChild(trackedDiv); 

    incomeName.value = "";
    incomeAmount.value = "";  

} else {
    alert("Missing Income Info!");
}

}

2

Answers


  1. Your code is too long and includes unnecessary stuff, CSS is not necessary to use localStorage.

    As for how to use localStorage

    localStorage is key-value storage and both key and value should be string.
    If your keys are not string, they are automatically converted to strings.

    But it is good practice to make sure both keys and values are strings before trying to save them.

    Example

    
    let userChosenNumber = 7
    
    // setting a value
    localStorage.setItem("luckyNumber", userChosenNumber.toString());
    
    
    // getting a value
    // note: theNumber is string
    let theNumber = localStorage.getItem("luckyNumber");
    
    // updating the value
    localStorage.setItem("luckyNumber", "18");
    
    // deleting the key-value pair
    localStorage.removeItem("luckyNumber");
    
    // clearing the localStorage (everything will be deleted)
    localStorage.clear();
    
    
    Login or Signup to reply.
  2. localStorage

    The localStorage is a place where you can save your data and this data has no expiration date. Once the info is saved, it can only be removed if the user browser decides to clean up their browsing data.

    Some quirks about localStorage

    • It have a generous storage capacity(almost 5-10MB, depending on the browser)
    • Each site and subdomain has its own localStorage
    • The syntax is straightforward
    • The data is saved locally and can’t be read by the server, which eliminates the security issue that cookies present

    What it is safe to save into the localStorage?

    Non-sensitive information, like for example, user preferences or the user cart list. Do never store personal information or authentication keys.

    Understanding localStorage

    As you said, you can create, read, and update key/value pairs in localStorage as follows:

    Creating entries

    You can create entries for the localStorage object by using the setItem() method. This method takes two arguments, the key and the corresponding value.

    let key = 'Item 1';
    localStorage.setItem(key, 'Value');
    

    Reading the entries

    To read the entries, use the getItem() method. The getItem() method takes one argument which must be the key. This function will return the corresponding value as a string:

    let myTask = localStorage.getItem(key);
    

    To update entries

    Updating entries is done with the set setItem() method. Again, it takes two arguments, the key that you want to update and the value that you want to update for that corresponding key.

    localStorage.setItem(key, "New value");
    

    Deleting entries

    The removal of an item in the localStorage is done by the removeItem() method. This method takes one argument which will be the key that you want to delete.

    localStorage.removeItem(key);
    

    There is also another method to clear all your items from the localStorage which is the clear() method:

    localStorage.clear();
    

    Observation about storing non-string values

    The localStorage can only store strings, and to workaround this if you want to store an object, use the JSON.stringify() to convert the object to a string.

    let taskList = [];
    const task = { description: "Study localStorage" };
    taskList.push(task);
    localStorage.setItem("tasks", JSON.stringify(taskList));
    

    To get back the stringified value that was once set, you need to convert back the stringified value to an object. This is done by the JSON.parse() like so:

    let item = JSON.parse(localStorage.getItem(key));
    

    I suggest that it might be worth you to try to set an object item directly into the localStorage(without converting the object into string) so you can see what and check what it actually stores in that case.

    How to see the stored localStorage items from your browser

    So, now that you saved items into the localStorage you might want to check if it’s all there. For Google Chrome, for example, you can go there by opening your browser, clicking on the "three dots" on the top right of the browser, then "More tools" and then "Developer tools". You can use the shortcut ⌥ Opt + ⌘ Cmd + I or ⇧ Shift + ⌘ Cmd + C instead. In this new developer tools section go to "Application" and on the left side menus click on "Local storage".

    Link reference from DigitalOcean:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search