My value is overridden in LocalStorage

0

I'm trying to add data in LocalStorage through a form. However, it always overrides the value and the key that I had given does not appear (it gets 1).

In this snippet of code it is when it takes the user object (it is an input) and sends to the 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:

Note that the key is not the one I set (user). And consequently, when I make other inserts, with other keys, it replaces the value.

    
asked by anonymous 28.03.2018 / 22:31

2 answers

0

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

    
28.03.2018 / 22:49
0

You can store a json object in the 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>
    
28.03.2018 / 22:51