Add object in LocalStorage [object Object] [duplicate]

2

I've added an object in LocalStorage as follows:

user: {
        authenticated: false,
        email: '',
        id: '',
        cpf: ''
}

localStorage.setItem('userData', this.user)

When I'm going to recover, localStorage.getItem('userData') is returned [Object Object] and I can not access the properties of the user object.

jsFiddle

What's wrong?

    
asked by anonymous 23.10.2018 / 15:39

2 answers

3

localStorage stores key value. To store a javascript object you must serialize this object using JSON.stringify :

localStorage.setItem('userData', JSON.stringify(this.user))

Returno

  

"{" authenticated ": false," email ":" "," id ":" "," cpf ":"

    
23.10.2018 / 15:45
3

Try to convert the object to a string JSON and then parse to retrieve it

localStorage.setItem('userData', JSON.stringify(this.user));

userData = JSON.parse(localStorage.getItem('userData');
    
23.10.2018 / 15:44