The mounted function in VueJS is encountering an issue where the data property is being

After making a GET request using Axios, I am successfully receiving data. However, I am facing an issue where I cannot access the application's data properties within the mounted function to store the results of the request. When I log this.productList, it returns undefined. Can someone help me troubleshoot this problem?

new Vue({
    el: '#products',
    data: function(){
        return{
            test: 'Hello',
            productList: null
        }
    },
    mounted: function(){
        axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response){
            console.log(response.data);
            console.log(this.productList)
        }).catch(function(error){
            console.log(error);
        })
    }    
})

Answer №1

When working within that particular function, the keyword this does not represent your vue instance; it carries a different meaning.

To address this issue, you can create a temporary variable to store the value of this from the outer function, like so:

mounted: function() {

  let $vm = this;

  axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then(function(response) {
    console.log(response.data);
    console.log($vm.productList)
  }).catch(function(error) {
    console.log(error);
  })
}

Alternatively, you could utilize arrow functions for a cleaner solution:

mounted: function() {

  axios.get('https://api.coindesk.com/v1/bpi/currentprice.json').then((response) => {
    console.log(response.data);
    console.log(this.productList)
  }).catch(function(error) {
    console.log(error);
  })
}

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

You cannot use res.json before res.redirect in Express.js

Hey there, currently I'm utilizing the express module in Node JS res.json({ auth: true, token: token, message: "success" }); res.redirect('/'); I need to send some JSON data first and then redirect. However, I encountered this err ...

javascript limitation on self-executing code

I am facing an issue with my HTML file that contains self-executing JavaScript code (I specifically need the JavaScript to be internal, not from an external file). Upon inspecting in Chrome, I encountered the following error message: Refused to execute ...

VUE array values not displaying flex-row properly

I've been working on creating an array of items in Vue and trying to use Tailwind CSS to make them flex-row, but I can't seem to get it right. Maybe there's something about the flex-row feature in Tailwind CSS that I'm missing. <div ...

Having trouble setting breakpoints in Chrome DevTools for my Vue application

Recently, I've encountered an issue where I am unable to place breakpoints in my Vue components as all the line numbers are greyed out. This problem started after updating Chrome to version 102.0.5005.63 from 86.0.4240.75. Could this be related to usi ...

What steps should I take in Three.js to make the "terrain" look three-dimensional?

Currently, I am in the process of developing a 3D terrain using Three.js along with ImprovedNoise.js. Utilizing the examples provided on the Three.js website, I have successfully created what appears to be terrain. However, my issue lies in the fact that i ...

Using JSF to make AJAX calls to PrimeFaces components

Hey, I'm looking to periodically call a back bean from a JavaScript function in order to refresh a panel on my page without refreshing the entire page. Here's the script I've written: $('#submitbutton').click(); <h:commandButt ...

NavLinkButton - add style when active or selected

I'm working with a list of NavLinks: const users = Array.from(Array(5).keys()).map((key) => ({ id: key, name: `User ${key}`, })); <List> {users.map((user) => { return ( <ListItem disablePadding key={user.id}> ...

What are the steps to creating an animated column chart using the aspx chart control?

I successfully implemented a column chart using the asp Chart control on a button click. The next step for me is to add a timer to animate the display of each column when the page loads. I would like to achieve this without relying on any external librar ...

When using Node Puppeteer, if the page.on( "request" ) event is triggered, it will throw an error message stating "Request is already being handled!"

I am currently utilizing puppeteer-extra in conjunction with node.js to navigate through multiple URLs. During each iteration, I am attempting to intercept certain types of resources to load and encountering the error below. PS C:\Users\someuser ...

Development of client and server using socket.io in node.js

I am trying to set up a basic demo using socket.io from http://socket.io The server (app.js) is functioning properly. However, I am encountering issues with the client side: <script src="/socket.io/socket.io.js"></script> <script ...

Filtering data attributes in jQuery for multiple elements

I have a variety of cars listed for sale on my website, along with five different filters: Make Model Year Mileage Price There are multiple options under each filter that users can select to refine their search. When users choose one or more options wit ...

What could be causing my Google Places nearby search to display atmosphere and contact information even when all fields are properly specified?

I created a fun game for the kids in my Scout troop to play while we're stuck at home during lockdown (www.riddlesdenscouts.org.uk/monsters). I'm noticing charges on my bill for contact and atmosphere data from my local search, even though I onl ...

Easily pass parameters to an event handler in a stateless component without the need to create a new reference of the handler every time the component re-re

// @flow import React from 'react'; import Input from 'components/Input'; import logo from 'assets/images/svg/logo.svg'; import styles from './style.module.css'; type TodoMethod = string => void; type TodoProps ...

What is the best way to connect socket.io to multiple instances of HTTPServer?

My Express server is set up to listen on both HTTP and HTTPS: Above, you can see the code snippet where I create the server instances for both HTTP and HTTPS protocols using Express. Currently, I am facing an issue with socket.io as it only listens to on ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

Difficulty in packaging JavaScript resources within Laravel Project

Having trouble setting JS functions as global in my project: In the 'resources\js"', I have: numerosALetras.js: /////////////////////////// function unidades_nal(n){ ... } function decenas_nal(n){ ... } function centenas_nal(n){ ...

User not authorized. Node/Mongo user not found

Hi there! I am currently working on creating a basic authentication login system using MongoDB and passport.js. The sign-up functionality is working fine, but I am facing issues with the login process. I have searched extensively online for a solution, but ...

What could be causing this issue with the ng-bind and ng-show directives not functioning as expected?

Attempting to show data retrieved from Google's Place Service. Oddly enough, the object can be logged to the console within the controller, but the directives in the HTML file remain blank. Since no map is being used, a div element was passed as the n ...

Assign a predefined object class as a set literal to the Input property of a component

My component has an @Input property called Options: @Component({ ... }) export class MyComponent { @Input() Options: Foo; ... } In the ParentComponent.html file, I pass an anonymous object as the input value: <My [Options]="{prop1:true, prop2:f ...

Creating custom Bootstrap Card Groups by dynamically generating the specified number of cards with Angular directives

I am currently using Angular 9.1.8 for my project. For my Angular component, I have implemented Bootstrap Card Groups and Cards to display a large result set of cards in rows with more than two cards per row. Below are four example cards: <div class=&q ...