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

I often find myself feeling unsure when I incorporate conditional logic in JSX within Next.js

Hello, I am currently using Next.js and encountering an issue with using if/else in JSX. When I use if conditions, the classes of elements do not load correctly. Here is my code: <Nav> { login ? ...

Trouble With Ajax Submission in CakePhp: Issue with Form Serialization

In my attempt to utilize ajax for sending an array of objects along with serialized form data, I encountered a problem. The issue arises when I include the array in the ajax data along with the serialized form data. This results in the serialized form data ...

Encountering difficulty accessing the object from the props within the created method

After retrieving an object from an API resource and storing it in a property, I encountered an issue where the children components were unable to access the object inside the created method. This prevented me from assigning the values of the object to my d ...

Encountered an issue while attempting to retrieve the access token from Azure using JavaScript, as the response data could

Seeking an Access token for my registered application on Azure, I decided to write some code to interact with the REST API. Here is the code snippet: <html> <head> <title>Test</title> <script src="https://ajax.google ...

Pass the returned variable value from a request.get call to another function in NodeJS Express

I have a situation where I am calling a function that makes a request to get some JSON data and then fills in the variables from my router.get method. The issue I am facing is that the variables are getting their value inside the callFunc function, but wh ...

The function cb() was never executed during the installation of @vue/cli

Hey everyone, I'm new to this and currently facing an issue while trying to set up vue cli for frontend development using npm. After running sudo npm install -g @vue/cli, the following output shows up: [18:00 vue]$ sudo npm install -g @vue/cli npm W ...

What is the best way to incorporate a mute/unmute button into this automatically playing audio?

Seeking assistance in adding a mute button for the background sound on my website. Can anyone provide guidance on how to achieve this? Below is the HTML code responsible for playing the sound: <audio id="sound" autoplay="autoplay" ...

Can you explain the purpose of this function on Google PlusOne?

Within the code snippet below: (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByT ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Easily automate button clicks on a new tab website

Seeking assistance below, following codes are sourced from "example.com" as assumed: <a href="http://www.example.org" target="vo1" onclick="gp(1)" rel="nofollow">Click Me</a> Upon clicking on ...

Can an onload function be triggered within the location.href command?

Can a function be called onload in the location.href using jQuery? location.href = getContextPath() + "/home/returnSeachResult?search=" + $('#id-search-text-box').val() + "&category=" + $('#search_concept').text() + "onload='j ...

A helpful guide on incorporating data from one component into another component in Vue.js

Recently, I started working with Vue and I am facing a challenge in transferring an array from one component to another. The first component contains the following data that I need to pass on to the second component: const myArray = []; Both components a ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Merge these two NPM packages together

Two npm projects exist: web-api (a library) and UI. The web-api utilizes gRPC-web to interact with the backend before converting it into a simple JavaScript object. In the UI, Vue.js is used in conjunction with web-api. Objective: merge these two project ...

How can I pass a dynamic scope variable to a JavaScript function in AngularJS that is being updated within an ng-repeat loop?

In my HTML, I have an ng-repeat loop where a variable is displayed in table rows. I want the user to be able to click on a value and pass it to a JavaScript function for further action. The code snippet below showcases my earlier version which successful ...

Loading JavaScript in the background using Java and HtmlUnit

I am currently facing a challenge while navigating a website using HtmlUnit. This particular website adjusts certain buttons and displays or hides certain elements based on JavaScript events. For instance, there is a text input box along with a button th ...

AngularJS - Sending configuration values to a directive

I'm trying to figure out how to pass parameters (values and functions) to an Angular directive. It seems like there should be a way to do this in Angular, but I haven't been able to locate the necessary information. Perhaps I'm not using th ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

Calculating a 30-minute interval between two given times using JavaScript/jQuery

My goal is to generate a list of times between a specified start and stop time, with half-hour intervals. While I have achieved this using PHP, I now wish to accomplish the same task using JavaScript or jQuery. Here is a snippet of my PHP code which may ...

Switch the selected option in JQuery UI dropdown using a clickable button

I have a code snippet that is almost working. My goal is to change the selection of a JQuery dropdown select combobox using a separate button named "next". What I want is for the JQuery dropdown to automatically switch to the next selection every time I c ...