0👍
✅
Encode your object to JSON before storing it in localStorage
. The reason being is that many browsers treat localStorage
as a key/value pair strictly for strings meaning that you cannot store complex data types such as an object. By calling JSON.Stringify(obj)
you are converting your object to a string with JSON. Then later when you access the data you need to convert it back to an object by using JSON.parse(str)
.
For example, in your code, you would want to change this line
localStorage.setItem('loggedinUser', response.data.access_token);
To this, so you encode the object as a string
localStorage.setItem('loggedinUser', JSON.stringify(response.data.access_token));
Then when you retrieve the data you would change your getter from
var searchItem = localStorage.getItem('anonymous_id');
to
var searchItem = JSON.parse(localStorage.getItem('anonymous_id'));
That way you are parsing the string back into a proper datatype
Source:stackexchange.com