const headers = new Headers({ 'access_token' : accToken, 'Content-Type': 'application/json', }); axios.post(baseURI, data, { headers: headers }) .then((response) => { this.users = response; }, (error) => { if (error) { this.errorMessage = error.response.data.message; } }).catch(error => { //this.errorMessage = error.response.data; }) },
Error when trying to retrieve/get data from the local storage?
I have created a login form using vuejs from which data is getting stored in the local storage, but I want to retrieve data from local storage for search purpose.
In the localstorage, i have attached screenshot. Where in my code tried getting the values.
Advertisement
Answer
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