My value is replaced in Localstorage

Asked

Viewed 132 times

0

I’m trying to add data to Localstorage through a form. However, it always replaces the value and does not appear the key I had determined (it is as 1).

In this code snippet is when it takes the user object (it is an input) and sends to Localstorage only the "user.name". It sends the value.

register(user: User) {
    this.user = new User;
    window.localStorage.setItem('user', user.name);
}

Result in Localstorage :

LocalStorage

You can see that the key (key) is not the one I set (user). And consequently, when I make other insertions, with other keys, it replaces the value.

2 answers

0


It was browser problem (opera). If someone in the future has the same problem as me, test your application in another browser.

0

You can store a json object in localstorage. If you are using jquery, you can apply JSON.stringfy(obj) and store the object verbatim.

var objs = {
  list: []
};

$(document).ready(function () {

  objs.list.push({nome: '', id: 1});
  
  //PARA ADICIONAR
  localStorage.setItem('nome', JSON.stringify(objs));

  //PARA PEGAR
  objs = JSON.parse(localStorage.getItem('nome'));
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Browser other questions tagged

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