Retrieve and display the total from a specific column in Vue using an API

I have an API that retrieves the total sum from a column in MySQL and returns it as JSON data. My goal is to display this data using Vue JS.

$stmt = $db->prepare("SELECT ROUND(SUM(total_amount), 2) as TotalAmount FROM orders");

$result = $stmt->fetch(PDO::FETCH_ASSOC);

echo json_encode($result);

The JSON result is:

{
    "TotalAmount": "2645.09"
}

To display this data, I am using Vue Js and passing it to a specific div element.

<div id="app" class="peer">
      <span>{{ TotalAmount }}</span>
</div>

<script>

  new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
    axios
      .get('https://api_url.php')
      .then(response => (this.info = response))
  }
})
</script>

Despite my efforts, I am unable to see the sum value displayed in my div. Additionally, the Vue developer tools are not functioning for me to check if the value is actually being retrieved. Should I consider a different approach for accessing the API?

Answer №1

Your code is currently setting the info variable with the result of axios.get(...) which returns { TotalAmount: "2645.09" } from your REST call.

There are a few issues with your current implementation:

  1. When you use then(response => (this.info = response)), it sets info to the entire response object from axios, not just the data from the REST call. To fix this, set info to response.data or destructure the object like so: then({ data } => (this.info = data))
  2. In your template, you are referencing TotalAmount which is not a recognized attribute in your component.

To update your component properly, follow this example:

<template>
  <div>
    <span>{{ totalAmount }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      info: undefined,
    };
  },
  async mounted() {
    const { data } = await axios.get('https://api_url.php');
    this.info = data;
  },
  computed: {
    totalAmount() {
      return this.info?.TotalAmount;
    },
  },
};
</script>

By using a computed property totalAmount, you can prevent errors such as 'Cannot read property TotalAmount of undefined'.

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

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Having Trouble with Bootstrap 4 JQuery Responsive Tabs? Check out the provided code snippet for a solution

So I have included a code snippet to showcase the issue. In my current code, I am using a jinga forloop to generate the cards. Each card contains responsive tabs. However, when you click on the tabs of card 2 to view its data, it ends up displaying the d ...

Sending the same element to a personalized filter repeatedly

Is there a better way to convert a string to a JavaScript date object before using the Angular date filter? The custom filter, stringToDate(), has been implemented and integrated into the code snippet below. <div ng-repeat="blogPost in blogPosts" class ...

The onprogress event for the XMLHttpRequest object threw an error due to an Uncaught SyntaxError, indicating

I have implemented an ajax function successfully However, I am facing an issue where when using onprogress, I sometimes receive incomplete HTML response and the console displays Uncaught SyntaxError: Invalid or unexpected token but the function still cont ...

Vue - receiving the output of a synchronous function

I'm having difficulty displaying the synchronous results of the method provided below. I am invoking the method from another method: var result = this.getVendor(id) console.log(result) Below is the fetch method code: methods: { async getData(i ...

Script written in PHP to retrieve text from a website, then translate and save it onto a local storage

Is there a way to save text from a website to a local file? The script should perform the following actions: Visit this website (fake site) http://website/webtv/secure?url=http://streamserver.net/channel/channel.m3u8**&TIMESTAMP** where TIMESTAMP ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

Is it better to let the old flash message fade away before introducing the new one?

I'm a beginner when it comes to jQuery. I have a form that calculates and displays the result in a flash message. My desired behavior is as follows: When the form is submitted for the first time, the flash message with the results should fade in. For ...

Loop fails to collect all values from the array

I am attempting to create two consecutive loops that will iterate through an array of customers and extract all the fruits from each customer's list. I initially tried using nested for loops, but this only provided me with the first fruit from each cu ...

jQuery show/hide functionality allows you to toggle the visibility of elements

I am looking to create a toggle button that expands the menu-wrapper width and hides the sidebar when clicked. Here is the initial CSS styling: #my-wrapper { Width:500px; } #sidebar-wrapper { width:200px; } Upon clicking the button, the CSS will update ...

Why is Ajax/FormData rounding my decimal values?

When sending data from a form to my PHP script, I am utilizing the new FormData() method to retrieve the values. However, there are additional values that I append later on which are not part of the form: var fd = new FormData(document.getElementById(&apo ...

Error: discord-webhooks causing SyntaxError due to an unexpected identifier in JavaScript code

I am currently working on a javascript project to set up a webhook for Discord. The URL has been removed for privacy reasons. const DiscordWebhook = require("discord-webhooks"); let myWebhook = new DiscordWebhook("removedtopostonstackexchange") myWebhook. ...

Is there a way to address the sporadic behavior of rxjs combineLatest when used in conjunction with ReplaySubject

My current struggle lies within this particular example: const r1 = new ReplaySubject(2); const r2 = new ReplaySubject(2); r1.next('r1.1'); r1.next('r1.2'); r2.next('r2.1'); combineLatest([r1, r2]).subscribe(console.log); // ...

Explaining the functionality of jQuery validation code

While exploring online tutorials, I stumbled upon a fascinating guide that makes use of jQuery and a validation plugin to validate form input. You can view the live example here: http://jsfiddle.net/nK7Pw/. Everything seems to be working perfectly, but o ...

Setting up Highcharts version 7 heatmaps with npm in an Angular 6 environment

I am currently having an issue with initializing the heatmap lib in Highcharts 7.0.1 within my Angular 6 app via npm. Despite successfully running basic charts like line, spline, bar, etc., when following the documentation for the heatmap initialization, I ...

What is the process for turning off caching in CORS-Anywhere?

Encountering an issue with CSRF token validation while making a POST request to an endpoint on a different server using cors-anywhere. The error occurs because the CSRF Token passed to the cors-server is cached, leading to validation failure. Referenced a ...

ng-change not firing when selecting from ng-options list

I am struggling with this code snippet <select ng-model="trabajadores.orderSelected" ng-options="excel for excel in trabajadores.csv.result[1]" ng-change="console.log('changed')"> </select> Despite my best ...

What is the best way to apply styling to an image that is contained within the document.write function?

I'm looking to customize the design of this cat image, but I'm struggling to locate where to incorporate the div class. It's likely a basic step, but as a beginner in JavaScript, I'm hoping that someone can assist me. document.write(&ap ...

Managing arrayBuffer in hapi.js: A Comprehensive Guide

I am struggling to upload an arrayBuffer to my server and save it to a file. On the client side, I am using axios, and on the server side, I have implemented Hapi js. However, I am facing difficulties in extracting data from the request in the Hapi handler ...

The functionality of item.classList.toggle() in HTML+CSS+JS fails to execute

I have been working on a program that aims to flip a card when it is clicked. The JavaScript code I have written for this functionality is as follows: /* Card flipping onclick */ import "./Stylesheets/FlipCardStyle.css" var cards = document.quer ...