How to do localStorage.setItem('nameserver', 'value') and make the nameserver always change if there is already one with the same name?

Asked

Viewed 111 times

1

I made a code where when clicking on a button it makes a function that stores a value in the browser promprio, follow the example below:

function favoritar(){
var SalvarURL = document.URL

localStorage.setItem('favorito', SalvarURL)
}

here it simply saves a "favorite" with the URL of the current page in the browser’s local storage.

Hence, I wanted to make sure that if there is already a "favorite" it creates another "favorite" but with the different name, like... "favorito2" and if there is already a "favorito2" it creates the "favorito3" and so on. and if possible, if there is already a "favorite" with the same url, it denies and a window.Alert saying for example that "This is already in your favorites".

I hope I was clear kkkk. anyone who can tell me whether this is possible or not, and if it is, can help me do it I would be very grateful, even in my heart <3.

2 answers

0

You can do it this way:

function favoritar(url){
var SalvarURL = url;

var favorito = 'favorito';
var count = 1;

while(true){
    var itemJaExistente = localStorage.getItem(favorito); // caso esse item não exista, getItem retornará null
    if(!itemJaExistente) { 
        localStorage.setItem(favorito, SalvarURL);
        break;
    } else if (SalvarURL === itemJaExistente) { // verifique se o valor que você está tentando salvar já foi salvo antes
        alert("Essa url já foi salva!!");
        break;
    } else { // atualize o nome do seu item e continue o loop
        count++;
        favorito = 'favorito' + count;
    }
}}

Checking that this URL has already been added only works if no item is removed from the localStorage, so to add a new item, you must go through all the previous items (from favorite to favorite), so you can do this check.

Another way to solve this problem, perhaps a little more robust, is to store all these Urls inside an array in localStorage:

function favoritar(url){
var SalvarURL = url;

var favorito = 'favorito';
var urls = JSON.parse(localStorage.getItem('urls'));
if(!urls) { // crie o item caso ele ainda não exista
    urls = [];
}

if(urls.includes(url)) { // verifique se sua url já foi adicionada
    alert("Essa url já foi salva!!");
} else { // adicione a url
    urls.push(url);
}
localStorage.setItem('urls', JSON.stringify(urls)); // atualize o item no localStorage
}

0


I hope to help in your doubt. I will try to show a solution, perhaps complementary or alternative to the @pedro_andrade, which we will create a manual script in an imperative way, since the localStorage API is simple and limited (that is, it does not equal a database, but does not take it as a criticism) so that we can incrementally save the favorito and check all keys and check whether the URL informed already exists. Follow the commented script to help and try to run to see if it works as Voce wishes. Note: the code may be cleaner and more modular, but what I want to pass is logic.

function favoritar() {
    // const salvarURL = document.URL;
    const salvarURL = document.querySelector('[name="url"]').value.trim();

    // vamos verificar se um ID ja existe
    let id = +localStorage.getItem('favId');

    // caso nao exista, entao assumimos que nao existe nada salvo
    if (!id) {
      id = 1; // valor inicial
      localStorage.setItem('favId', id); // salvamos o id no campo 'favId'
      localStorage.setItem(`favorito${id}`, salvarURL); // fica: favorito1

      return;
    }


    // o codigo seguinte server para verificar se a URL ja existe nos favoritos
    let urlExiste;

    for (let i = 1; i <= id; i++) {
      // se o favId for 5, vamos fazer um loop de 5 iteracoes e vamos comparar
      // cada uma das urls para verificar a igualdade

      const url = localStorage.getItem(`favorito${i}`); // favorito1, favorito2, favorito3...

      if (salvarURL === url) {
        urlExiste = true;
      }
    }

    // caso alguma url ja exista, alertamos ao usuario
    if (urlExiste) {
      window.alert('URL informada ja existe!');
      return;
    }

    // caso a url informada seja valida, salvamos ela e incrementamos o favId
    id = +id + 1;
    localStorage.setItem('favId', id);
    localStorage.setItem(`favorito${id}`, salvarURL);
  }

Now let’s create a h2 with bookmarks and their respective urls. Let’s put a div empty html with a name class favoritos where the bookmarks saved on localStorage will be displayed. In html:

<div class="favoritos">
</div>

Now right after the code line localStorage.setItem(`favorite${id}`, salvarURL), let’s add the function adicionaTituloFavoritos() where I commented so that it is explained the functioning of the code:

    // ... 
    // invocamos a funcao toda vez que um favorito for adicionado.
    adicionaTituloFavoritos();

    function adicionaTituloFavoritos() {
      // selecionamos a div onde serao exibidos os h2
      const favoritos = document.querySelector('.favoritos'); 

      favoritos.innerHTML = ''; // damos um reset para limpar o 
                                // conteudo da div

      for (let i = 1; i <= id; i++) {
        const url = localStorage.getItem(`favorito${i}`);
 
        // se houver uma url, vamos criar um h2
        if (url) {
          const h2 = document.createElement('h2');
          h2.textContent = `favorito${i} - ${url}`; // texto do h2

          favoritos.appendChild(h2); // adicionamos a div dos favoritos
        }
      }
    }

I hope my code is clear and I’ve helped you.

  • That helped me VERY much! Thank you! Besides, I also wanted to know if it has how to (concerteza has) put all "favoritoN" in some H2, if you have 3 "favorites" it puts 3 H2 with the name of the favorite that in the case would be "favorito1", "favorito2" and "favorito3", so ok example.

  • has yes, just follow the logic to perform the loop and use methods of document to create a tag h2 and insert bookmarks and urls. If you want I can add this code in my reply.

  • Yes, Please! this would help me a lot and maybe help other people with the same "problem" or sla kkk.

  • added, see if my explanation helped you.

  • Okay, I’ll test here, anything warning here whether it’s worked or not :)

  • I tested the code to add to an H2 and a part of the code is in error. &#xA;for (let i = 1; i <= id; i++) {&#xA; That part of the code, the part of <= id. i++. In the console it says that the "id" is not defined, and I think it is because the "id" is inside another function where the variable is a "Let", (so to deduce) you can help me to solve this?

  • @3nder where Voce placed the part where it adds the h2? it has to be placed after the localStorage.setItem(favorite${id}, salvarURL); and before closing the key }

  • @3nder if you want I can post the complete code, because in my tests work normally. I think Voce put the function adicionaTituloFavoritos() outside the scope of function favoritar()

  • A, true. I analyzed and it was just that, sorry kkkkkk. Thank you and bro!

Show 4 more comments

Browser other questions tagged

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