What could be causing the failure of the API data to display on my Vue template?

I've been racking my brain over this issue. Vue is new to me and I'm stumped as to why it's not functioning correctly.

This is my template...

<template>
<div>
  <div v-if="loading" class="loading">Loading...</div>
  <div v-if="dbhs">
      <h1>adfoij</h1>
      <p class="mb-0" v-if="dbhs.length === 0">
          You have not added any DBHs.
      </p>
      <div v-else>
          <div v-for="dbh in dbhs">{{dbh.dbh}} - {{dbh.count}}</div>
      </div>
  </div>
</div>
</template>

And this is my script...

<script>
export default {
    data() {
      return {
            loading: true,
            dbhs: null
        };
    },
    created() {
        this.retrieveDbhs();
    },
    methods: {
        ajaxAxiosGetFunc: async function (url) {
        var output = '';
        await axios({
            method: 'post',
            url: url,
            data: {},
            responseType: 'json',
        })
        .then(function (response) {
            //output = JSON.parse(response.data);
            output = response.data;
        }.bind(this))
        .catch(function (error) {
            console.log('ajax error');
        });
        return output
      },

        getDbhs: async  function(){
            var estimate_id = document.getElementById('estimate_id').value
            var output = await this.ajaxAxiosGetFunc('/estimate/'+estimate_id+'/getTreesSummary/dbh'); 
            this.dbhs = output;
            console.log(output);
            this.loading = false;
        },
  }
}
</script>

The data is coming back from the API and shows up in the console, but the length of dbhs remains at 0.

Any suggestions or solutions?

Answer №1

The issue here arises because the method utilizes the function keyword, which overrides the context of this that normally refers to the vue instance. To resolve this, simply replace the anonymous function with an arrow function like so:

getDbhs: async () => {
    var estimate_id = document.getElementById('estimate_id').value
    var output = await this.ajaxAxiosGetFunc('/estimate/'+estimate_id+'/getTreesSummary/dbh');  // called asynchronously to wait till we get response back
    this.dbhs = output;
    console.log(output);
    this.loading = false;
},

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

Simple steps for Mocking an API call (Get Todos) using ComponentDidMount in React with Typescript, Jest, and Enzyme

About the application This application serves as a basic To Do List. It retrieves tasks from an API located at https://jsonplaceholder.typicode.com/todos?&_limit=5. Objective of the project The main goal is to test an API call that triggers ...

Tips for setting up a webpacked vue.js application with an express/koa backend!

Struggling with setting up a vue.js project for easy debugging in combination with a koa server? The cross-env NODE_ENV=development webpack-dev-server --open --hot command from the webpack-simple generated configuration looks promising, but how should it b ...

Combine a segment from two arrays into a single array

I have two arrays and I want to merge them into one while extracting only certain elements... I am using axios with vueJS. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: Nombredejours: 1.5 Task: {id: "52edcb0e-450f-4de7-b70d-b63e0 ...

AssertionError: 'assertEquals' is not recognized in compiled WebDriverJS

I'm facing an issue with the webDriverJS library. After downloading the project and building the js file "webdriver.js" following instructions from the wiki and this post on Selenium WebDriverJS Using in Browser, I am unable to use the function "asse ...

Increasing the name attribute with Jquery cloning

I'm interested in duplicating the addDriverContent (which is currently functional) and updating the numbers in the name attribute from name="description" to name="description2", name="description3" on the duplicates Additionally, if anyone knows how ...

What is the best method for dynamically loading CSS using JavaScript?

Due to a certain condition I have, I am unable to load some CSS and JS in my HTML. As a solution, I've decided to dynamically pull them using $.get(). While I have successfully tested pulling and executing js remotely, I am facing some challenges when ...

What is the best way to condense a repetitive method declaration and make it more concise?

I'm facing a situation where I have declared similar const values. Here's my current setup... import React from 'react' function Component_a() { const x = 5; const y = 10; const image_a = [...Array(x)].map((e, i) => ...

Is it possible to modify CSS properties using Ajax?

I am attempting to dynamically change the background color of a div using AJAX to fetch the user's specified color from the database. Below is the code snippet I am using: $.ajax({type: "POST", data: {id: id}, url: "actions/css.php", success: functio ...

Setting up Socket.io results in numerous transport polling GET requests being initiated

I have set up an express.js server-side and followed the socket.io guide. However, I am facing issues with the socket connection not being successful, and there seems to be a high number of unexpected GET requests like this: https://i.stack.imgur.com/GDGg ...

Incorporating a Link into a Radio Button component in Material-UI using react-router

Greetings! I have two radio buttons and would like to include a link. I attempted to achieve this in the following manner: <RadioButton value="/searchByArtistAndName" label="Artist and Name" style={styles.radioButton} contai ...

How can I incorporate clearInterval into multiple methods effectively?

One of the challenges I faced was implementing the moveMarker method with setInterval to make my Marker in mapbox-gl move along my Routes Line. I also added a play button to trigger this function. Now, I want to create a pause button that stops the movemen ...

Steps for effectively deleting browsing history on Ionic

While testing my app on Chrome browser, I encountered an issue with clearing old views and cache. This is the process I followed to sign out of my app: https://i.stack.imgur.com/EGgRx.png Upon clicking Log out, the following code is executed: Auth.$s ...

Preventing page refresh with Javascript when clicking on CAPTCHA

I have been exploring a CAPTCHA tutorial on TutsPlus.com and I am facing an issue where the 'Incorrect Captcha message' keeps appearing, indicating that my user input through $_POST does not match the stored $_SESSION string. Upon investigating ...

Unable to redirect to Jade page in Node.js

I recently delved into the world of node js a few days ago. When I click on a button, a function with an ajax call is triggered. function goToUser(){ $.ajax({ url:"/users/UserPage", type:'get', async:false, su ...

Navigating through web applications can be made easier by combining Vue Router

In my applications, I have a variety of routes: GET /game/{any} For this route, Laravel auth middleware provides protection. Within this Laravel route, I plan to create a Single Page Application (SPA) and implement Vue router: const routes = [ { path: ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

Angular JS element cannot be located

My Angular object is not being passed when I write a new function, and I'm unsure why. The object, named person, is directly bound in the HTML and returns 2 items from the cardsCollection array. The function I'm attempting to create is called cl ...

Utilizing ng-hide or ng-show with a select box dropdown option

Can select box options be hidden using the ng-hide directive? http://jsfiddle.net/cr4UB/ <div ng-app ng-controller="Controller"> <select ng-model="myDropDown"> <option value="one">One</option> <option va ...

Exploring the powers of Vue.js computed properties and watchers

I recently came across this Vue guide on computed and watcher properties. One specific part caught my attention: this.debouncedGetAnswer = _.debounce(this.getAnswer, 500) inside the created property. My inquiry is Will this formula add this.d ...

Adjust the cell text overflow based on the width of the table

I am working with a table that has multiple columns. I want the first 3 columns to have a larger width than the others, specifically taking up 15% each for a total of 45% of the table's width. Currently, I am using this code in a sandbox environment: ...