when I'm try to convert string to object I get error ``:
Unexpected token u in JSON at position 0
Service
setUser : function(aUser){
//sauvegarder User
localStorage.setItem('User', JSON.stringify(aUser));
},
getUser : function(){
//récuperer User
return JSON.parse(localStorage.getItem('User'));
}
The first thing to do is to look at what you're trying to parse. My guess is that you'll find it's "undefined"
, which is invalid JSON. You're getting undefined
because you haven't (yet) saved anything to that key in local storage. undefined
is then converted to the string "undefined"
which JSON.parse
can't parse.
I usually store and retrieve things in local storage like this:
Storing (just like yours):
localStorage.setItem("key", JSON.stringify(thing));
Retrieving (this is different):
thing = JSON.parse(localStorage.getItem("key") || "null");
if (!thing) {
// There wasn't one, do whatever is appropriate
}
That way, I'm always parsing something valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With