How to save an To-Do-List in localstorage in javascript?

Asked

Viewed 299 times

1

It’s very simple what I want to do: In HTML there is a input where the person enters with the information, I pick it up and saved in the localstorage, but localstorage.setIten() it overwrites, so I want to save the information in a array and display on HTML within a li.

Ex: the person enters the input with the information = apple, pineapple, grape

I want to save her in the localstorage thus: Key would be "fruit" and Value would be [apple, pineapple, grape]

I’m sending the code I tried to do but got lost, someone could help me with the easiest way to do it ?.

Thank you.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <h1>Lista de Compras</h1>

    <input type="text"  id="input">
    <button id="button">Compras</button>

    <button id="delete">Deletar</button>

    <ul id="lista"></ul>

    <script>

        const buttton = document.querySelector('#button')
        const input = document.querySelector('#input')
        const lista = document.querySelector('#lista')
        const deletar = document.querySelector('#delete')

        let array = []
        
        buttton.addEventListener('click', () => {
            array.push(input.value)

            localStorage.setItem('compras', JSON.stringify(array))

            let aa = JSON.parse(localStorage.getItem('compras'))
            
            aa.map(x => {
                return(
                    lista.innerHTML = `
                        <li>
                            ${x}
                        </li>
                        `
                )
            })

            
            input.value = ''

        })

        window.addEventListener('DOMContentLoaded', () =>{
            lista.innerHTML = `
                <li>
                    ${localStorage.getItem('compras')}
                </li>
            `
        })

        deletar.addEventListener('click', () => {
            localStorage.clear()
            lista.remove()

            input.value = ''
        })
    </script>  
</body>
</html>
  • That’s right, I just think we’re missing a '{element}. innerHTML = ' before the map, and a '.Join("")' after, and instead of the local variable 'aa' use the 'array'.

  • I saw they gave a -1, the question got bad personal ? , could not understand. If you can help me, I appreciate.

  • Your question is similar to this: https://answall.com/questions/399129/localstorage-salvar-alguns-campos?rq=1

  • All right Leandrade, I looked before asking the question and it’s not what I want to do, I want to add an array in the Storage location and then read it in html. Thank you

2 answers

1


I did some research and performed tests and it is not possible to store array in localStorage it automatically converts the array in string, one array that would be an example var arrayFrutas = ['maça', 'abacaxi', 'uva'] by putting this array in the localStorage he becomes a string maça, abacaxi, uva. Unable to search elements for index or by value.

But there is a solution, like localStorage stores the data permanently until it is not "cleaned" with a clear(), you can take this string of localStorage separated elements by comma and with the method split() turn this string into an array.

The method split() divides a String in an orderly list of substrings, put these substrings in a array and returns the array.

Syntax:

str.split([separator[, limit]])

Then to put them on array, just make a for() to allocate them to elements <li>

*PS: It’s a much easier and practical way than what you’re doing.

Testing:

```html Document
<h1>Lista de Compras</h1>

<input type="text"  id="input">
<button id="button">Compras</button>

<button id="delete">Deletar</button>

<ul id="lista"></ul>

<script>

    const buttton = document.querySelector('#button')
    const input = document.querySelector('#input')
    const lista = document.querySelector('#lista')
    const deletar = document.querySelector('#delete')

    let array = []

    let storageArray = localStorage.compras? localStorage.compras.split(','):localStorage.setItem('compras', array);
    
    buttton.addEventListener('click', () => {
        if (input.value.length > 0){
        array.push(input.value)
        localStorage.compras.length > 0? localStorage.compras += ','+array: localStorage.compras = array;
        }
        

    })

    window.addEventListener('DOMContentLoaded', () =>{
        for (let i in storageArray){
            lista.innerHTML += `<li>${storageArray[i]}</li>`
        }
        
    })

    deletar.addEventListener('click', () => {
        localStorage.clear()
        lista.remove()

        input.value = ''
    })
</script>  
```
  • 1

    thanks for the help.

1

First of all, this code:

window.addEventListener('DOMContentLoaded', () =>{
            lista.innerHTML = `
                <li>
                    ${localStorage.getItem('compras')}
                </li>
            `
        })

You should iterate on the items from localStorage to avoid inserting only an array(string looking like array) and only appearing the array inside the li.

Rewrite this way, iterating over the saved items and adding them to the list:

window.addEventListener('DOMContentLoaded', () => {
  JSON.parse(localStorage.getItem('compras')).forEach(el => {
    lista.innerHTML += `
            <li>
                ${el}
            </li>
        `;
  })
});

JSON.parse(localStorage.getItem('compras')) to convert to actual array so we can iterate over it. Use += to concatenate the elements into the list. Use only the = will overwrite the data.

Then try using the value of array to recover all saved items, do the push of the new value, and array will have the old values and the new value. To see that the data has been persisted, take all the saved values and assign the items and make a console.log(items) to confirm that values have been saved. Then, in the list, just add the new value inside a li, only to show that the value was saved by inserting:

lista.innerHTML += `
                  <li>
                      ${input.value}
                  </li>
                  `;

in this way:

buttton.addEventListener('click', () => {
  const array = JSON.parse(localStorage.getItem('compras')) || [];

  array.push(input.value);

  localStorage.setItem('compras', JSON.stringify(array));

  let items = JSON.parse(localStorage.getItem('compras'));

  lista.innerHTML += `
                  <li>
                      ${input.value}
                  </li>
                  `;

  input.value = '';
});

Note that again I used += because I don’t want to overwrite the data already entered in the list. When reloading the page, the saved data will still be displayed.

  • Tip: Make a check to not save empty values.

Keep the rest of your code as is.

Complete code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h1>Lista de Compras</h1>

    <input type="text" id="input" />
    <button id="button">Compras</button>

    <button id="delete">Deletar</button>

    <ul id="lista"></ul>

    <script>
      const buttton = document.querySelector('#button');
      const input = document.querySelector('#input');
      const lista = document.querySelector('#lista');
      const deletar = document.querySelector('#delete');

      buttton.addEventListener('click', () => {
        const array = JSON.parse(localStorage.getItem('compras')) || [];

        array.push(input.value);

        localStorage.setItem('compras', JSON.stringify(array));

        let items = JSON.parse(localStorage.getItem('compras'));

        lista.innerHTML += `
                  <li>
                      ${input.value}
                  </li>
                  `;

        input.value = '';
      });

      window.addEventListener('DOMContentLoaded', () => {
        JSON.parse(localStorage.getItem('compras')).forEach((el) => {
          lista.innerHTML += `
            <li>
                ${el}
            </li>
        `;
        });
      });

      deletar.addEventListener('click', () => {
        localStorage.clear();
        lista.innerHTML = '';

        input.value = '';
      });
    </script>
  </body>
</html>


  • Thanks for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.