Having trouble accessing data from the local storage?

        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 encountered while attempting to fetch data from local storage?

I have successfully created a login form using vuejs that stores data in the local storage. However, I am facing issues when trying to retrieve data from local storage for search purposes.

I have provided a screenshot of the local storage where I attempted to access the stored values in my code.

Answer №1

Before storing data in your localStorage, make sure to encode your object to JSON. This is important because many browsers only accept strings in the localStorage as key/value pairs and do not allow complex data types like objects. By using JSON.Stringify(obj), you convert your object into a JSON string. When retrieving the data later on, remember to use JSON.parse(str) to convert it back to an object.

For instance, instead of this line of code:

localStorage.setItem('loggedinUser', response.data.access_token);

You should modify it like this to encode the object as a string:

localStorage.setItem('loggedinUser', JSON.stringify(response.data.access_token));

When fetching the data, change your getter from:

var searchItem = localStorage.getItem('anonymous_id');

to:

var searchItem = JSON.parse(localStorage.getItem('anonymous_id'));

This way, you are converting the string back into its original data type

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing Modules in NodeJS using Constructors or Object Literals

I am currently developing a nodejs application that needs to communicate with various network resources, such as cache services and databases. To achieve this functionality, I have created a module imported through the require statement, which allows the a ...

The ng-disabled directive is functioning properly, however it is not having any impact on the disabled attribute in

Having an issue with enabling or disabling a button based on the selection of a certain string from a dropdown menu. HTML <select ng-change="checkType()" ng-options="sth in sth for things"></select> <input ng-disabled="{{toggleDisable}}" ...

How can I implement disabling buttons for specific IDs in React?

I'm currently developing an interactive quiz application with React that features multiple choice questions. I've implemented state management to track and increment the user's score when they select the correct answer option, but there&apos ...

The combination of select2 and jsonform is not functioning properly

I am having trouble rendering multiple select2 with JSON form. $('#resource-form').jsonForm({ schema: { rest: { type: 'object', properties: { template_id: { type: "array", items: { ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

Step-by-step guide on transferring an HTML5 sqlite result set to a server using AJAX

Imagine I have a scenario where I receive a result set as shown below: db.transaction( function(transaction) { transaction.executeSql( 'SELECT col1, col2, col3 FROM table;', [],function(transaction, result){ //need to find a ...

Is there a way to categorize items by their name in JavaScript?

Currently working with Node, I am in the process of developing an ID3 tag parser to extract the title, album, and artist information from MP3 files. My next step involves organizing the retrieved data by grouping them according to the album name. In my p ...

Is the use of addEventListener("load",... creating an excessive number of XmlHttpRequests?

Consider a scenario where you have the following JavaScript code running in a Firefox plugin, aimed to execute an XmlHttpRequest on a page load: function my_fun(){ var xmlHttpConnection = new XMLHttpRequest(); xmlHttpConnection.open('GET', ...

Create data according to jQuery's AJAX data method

When editing in place using jQuery, if the code snippet seems too complicated, please refer to a simpler one. 'column2' => "RAJANgsfdgf" 'column3' => "SRARDHAMgsdfgdf" 'column4' => "40043433" 'column7' =&g ...

What are your thoughts on utilizing for loops within the same function in Vue to organize fetched data?

Currently, I am implementing a fetch request to retrieve data from an API. The data is then converted to JSON format and I would like to organize it into separate categories. For instance, tickets with the status "active" should be placed in one array whil ...

Validating Linkedin URLs with JavaScript for Input Fields

I've created a basic form with an input field for a LinkedIn URL. Is there a way to validate that this field only accepts valid LinkedIn URLs? Thank you! ...

Error: The $filter function in AngularJS is not recognized

I have been attempting to inject a filter into my controller and utilize it in the following manner: angular .module('graduateCalculator', []) .filter('slug', function() { return function(input) { ...

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...

Having trouble getting my app.get calls to work in the new Node Express project

Recently, I kicked off a new project and encountered a perplexing issue - my app.get method simply refuses to be invoked. The site keeps loading indefinitely without any content being displayed. Initially, I copied and pasted the code from another project ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

In the Vercel production environment, when building Next.js getStaticPaths with URL parameters, the slashes are represented as %

I've encountered an issue while implementing a nextjs dynamic route for my static documentation page. Everything works perfectly in my local environment, and the code compiles successfully. However, when I try to access the production URL, it doesn&ap ...

The transition from material-ui v3 to v4 results in a redux form Field component error stating 'invalid prop component.'

Since upgrading from material-ui v3 to v4, I am encountering an error with all my <Field> components that have the component prop. Error: Warning: Failed prop type: Invalid prop component supplied to Field. The Field component is imported from im ...

Completely enlarge this inline-block CSS div scan-line

I am looking to create a unique scan line effect that gradually reveals text from left to right, mimicking the appearance of a cathode-ray burning text into a screen's phosphors. The concept involves sliding across black rows with transparent tips. Y ...

What steps do I need to take in order to implement a basic ZeroClipboard copy-to-clipboard feature in jQuery on jsFiddle with just one click?

I'm having trouble implementing ZeroClipboard in a jQuery environment. My goal is to have the text within each div with the class copy copied when clicked. The following jsFiddle demonstrates the functionality with double click using the stable ZeroC ...

Should loaders be utilized in an Angular application?

Webpack configuration allows the use of various loaders, such as file-loader, html-loader, css-loader, json-loader, raw-loader, style-loader, to-string-loader, url-loader, and awesome-typescript-loader. Does Angular have built-in knowledge of loaders with ...