0

Im trying to create a small database with localstorage for a small project ( just to emulate a login ).

It's supposed to open two prompts to ask username and password and then store it in a Array of Objects. What happens is that I iniciate the first element of the Array with an Object of an admin and when after inserting the second user (it lets me add one more after the admin) it says that the Users(Array).push is not a function.

var name = prompt('Insert your name');
var password = prompt('Insert your password');

if(localStorage.length!==0){
    Users=localStorage.getItem('Users');
}else {
    var Users = [{
        name:'admin',
        password:'admin'
}];
}

var person = {
    name:name,
    password:password
}

Users.push(person);

localStorage.setItem('Users',Users);

Its supposed to store users and passwords as object inside the array as I load the page over and over again.

Thank you in advance for anyone willing to help

João Vieira
  • 121
  • 1
  • 9
  • https://developer.mozilla.org/en-US/docs/Web/API/Storage/getItem returns a string – SLaks Apr 11 '19 at 16:49
  • Possible duplicate of [Storing Objects in HTML5 localStorage](https://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) – ponury-kostek Apr 11 '19 at 16:50

1 Answers1

2

localStorage stores key/value pairs, but the value is stored as strings, not other data structures.

localStorage.setItem('Users', JSON.stringify(Users));

and then when you get it:

Users = JSON.parse(localStorage.getItem('Users'));

You are having an error because when you get it from localStorage it's not an Array.

Teh SoTo
  • 209
  • 1
  • 10