Storing API data in localStorage using VueJS: A step-by-step guide

As I work on practicing building a simple SPA with VueJS, one of my current tasks involves listening to an API and storing certain data in the browser's localStorage. However, my experience with VueJS is still limited, so I'm unsure about how to extract specific information from the API response and save it in the localStorage for logged-in users to access later.

The API provides a large amount of data, but at this stage, I am only interested in retrieving the user's email and name.

Here is the code snippet I have developed so far:

<script>
    import axios from 'axios';
  import jsonpAdapter from 'axios-jsonp';

  export default {
    data() {
      return {
        info: 'placeH',
        data: []
      }
    },
    mounted: function(){
      axios({
        url: 'APIplaceholder'
        adapter: jsonpAdapter
      }).then((res) => {

      });
    }
  }
</script>

My current challenge lies in figuring out how to specifically select and extract the required information (email and name) from the overwhelming data provided by the API and then store it in the localStorage.

I believe that saving this extracted information in a JSON file within the localStorage would be the most efficient approach.

Answer №1

localStorage stores only strings. When you use

localStorage.setItem("apiData", res.data)
, it will store the string "[Object object]" in localStorage, not the actual res.data object.

To properly set and get items from localStorage, you need to use JSON.stringify() and JSON.parse().

.then((res) => {
     localStorage.setItem("apiData", JSON.stringify(res.data));
});

To retrieve the data, you can do the following:

var data = JSON.parse(localStorage.getItem("apiData"));

Then you can access the data using the (dot) operator. For example: data.userName.

I hope this explanation helps clarify things for you.

Answer №2

When you receive a response object, it will contain a data property that holds the details of the requested user. Take a look at the following code snippet:

mounted: function(){
  axios({
    url: 'APIplaceholder'
    adapter: jsonpAdapter
  }).then((res) => {     
        localStorage["name"]=res.data.name
        localStorage["email"]=res.data.email
  });
}

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

Adding a line break in a Buefy tooltip

I am trying to show a tooltip with multiple lines of text, but using \r\n or is not working. <b-tooltip label="Item 1 \r\n Item 2 \r\n Item 3" size="is-small" type="is-light" position="is-top" animated multilined> ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...

Vue Cli 3: customization of output directory paths

I am looking for assistance in setting up the output paths for my final build. Here is what I need: Although my Vue project follows the default structure, the output paths are located outside this structure: Output HTML file: ../main/resources/ Output o ...

Styling for older versions of Internet Explorer (IE10 and earlier)

Could it be true that IE 10, 9, and others no longer support conditional statements? Is it also accurate to say that JQuery does not support the browser object above version 1.9? I am facing an issue with CSS rendering differently in Chrome and IE. A Goog ...

Having issues with v-for in Vuejs? It seems to be looping multiple times

<div v-for="item in items" :key="item.id"> <div v-for="accordion in accordions" :key="accordion.title" class="line" :class="{ green: accordion.text === 'AllaboutVue', red: accordi ...

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

Transfer the data from an XML element to generate a fresh element with an integrated value

I am looking to modify an XML file that contains multiple products by adding a new element with values from existing elements. Specifically, I want to add a new element to each product titled SKU, which should include the values of ProductOption, PurchaseO ...

Navigating horizontally with buttons in VueJS

I am searching for a way to implement horizontal scrolling using buttons in VueJS. The idea is to have a container with multiple divs arranged horizontally, and I wish to navigate through them using the buttons. If you want to see a similar solution using ...

Jumbling a word by shuffling its letters into a random order

The objective of the program is to take the word you input into a box, split it into an array of letters, and then shuffle them. Following that, it should capitalize the first letter and lowercase the rest before displaying the result in the same box. I a ...

Passing the IDs of other elements as arguments when invoking a JavaScript function

Greetings, as I work on a jQuery mobile app, a particular scenario has arisen that requires attention. <script> function showPanel(info) { alert(info.id); } </script> <div data-role=" ...

Is there a way to update the href attribute within the script section in vue.js?

I need to dynamically set the href attribute of a link based on data retrieved from a database and rendered in the methods section. <template v-if="header.value == 'ApplicationName'"> <a id="url" href="#" target="_blan ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

Getting information from my RESTful API and populating the array data property in my VueJS component

For several weeks, I've been immersed in learning Vue.js and building a Rest API backend using NodeJS express, which I'm eager to integrate. After successfully setting up the Rest API to deliver JSON data, my next challenge is to retrieve that js ...

My ejs page is not showing up because a variable has not been defined

I am facing an issue with an undefined variable causing my EJS page to not display properly when an if statement is included. Removing the if statement allows the page to render, but the presence of the undefined variable and if statement triggers an error ...

The style was not applied from because it has a MIME type of 'text/html', which is not a supported stylesheet MIME type, and strict MIME checking is turned on

I'm currently working on creating a Google web app that relies on a Google sheet in the backend. I prefer to develop locally in VSCode since the editor in Google Apps Scripts is quite limited. Additionally, I aim to incorporate Vue3 into my project. ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

The initialization of Firebase is not being completed before it is being called in other files

I am currently working on a vue project and I am attempting to integrate firebase. However, I have encountered an issue where my other JavaScript files like auth.js are utilizing firebase before it is properly initialized in my main.js file (which acts as ...

Javascript functions fail to execute as intended

I have a project called calc, which includes various functions such as init. Within this project, there are three buttons that I am adding to the div using jquery. When a user clicks on any of these buttons, it should trigger the inputs function. Based on ...

What is the best way to access an item within an item using HTML and AngularJS?

I attempted to retrieve a value from two dynamic objects using AngularJS. <div ng-controller="SampleController"> <div> {{item['111']['price']}} </div> within the SampleController $scope.item={111:{price:"232"},112:{ ...

Sharing markdown content between two Vue.js components

I have a markdown editor in View A which is displaying the result in the current View. My goal is to share this result with another page, View B. In View A, there is a button that allows the user to share the markdown result with View B. I am using a texta ...