Add object in Localstorage [Object Object]

Asked

Viewed 653 times

1

I have added an object to LocalStorage as follows:

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

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

When will I recover, localStorage.getItem('userData') is returned [Object Object] and I can’t access the properties of the object user.

jsFiddle

What’s wrong with it?

  • You seem to be saving an object and returning an object. I don’t understand the doubt.

  • @Andersoncarloswoss yes, the idea is to save the object and retrieve it.

  • So what’s the question? The object you took from localStorage wasn’t what you saved?

  • @Andersoncarloswoss is returning [Object Object] and not the object itself!

  • But this is an object. This is explicit. It can better describe which object was returned?

  • @Andersoncarloswoss just a minute I’ll add a Fiddle.

  • Ah, now I understand. What he returns is string "[object Object]". The lack of quotation marks there completely changes the meaning. So what happens is the one reported in the answer: it only accepts a value string, then you need to convert your object to string before saving.

  • @Andersoncarloswoss added a Fiddle in Vue.

  • @Andersoncarloswoss the error is different, the question that was badly asked but not duplicated. answer http://jsfiddle.net/ync9em23/1/

  • @Hudsonph but then you’re not even using the localStorage which is the source of the problem.

  • @Andersoncarloswoss exactly he shouldn’t even use it, since the object can be used directly

  • @Hudsonph But apparently he needs to persist the object and use it on other pages. The way you did the object will not remain persisted.

  • @Andersoncarloswoss in this case he needs to implement the Vue method and not do that trick.

  • @Hudsonph gambiarra? I don’t understand, this was a basic example to illustrate the problem.

  • @Hudsonph I see that you do not understand the problem, but it’s worth! and the question is duplicated yes.

  • @Marconi the purpose of using JSON.stringify and to send date display, you should have methods to manipulate the object

  • @Hudsonph the example I put in Fiddle is incorrect, but his intention was only to reproduce what happened.

Show 12 more comments

2 answers

3

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

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

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

3

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

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

Roundabout

"{"authenticated":false,"email":"","id":"","Cpf":""}"

Browser other questions tagged

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