What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my backend

http://127.0.0.1:8000/user/getamount
.

Below is the code snippet:

chart.js

import Vue from "vue/dist/vue.js";
import Vuex from "vuex";
import storePlugin from "./vuex/vuex_store_as_plugin";
import App from './App.vue'
import HighchartsVue from "highcharts-vue";
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(Vuex);
Vue.use(storePlugin);
Vue.config.productionTip = false;
Vue.use(HighchartsVue);
Vue.use(VueAxios, axios)


new Vue({
  el: "#app",
  render: h => h(App),
});

App.vue

<template>
  <div>
    <highcharts class="hc" :options="chartOptions" ref="chart"></highcharts>
  </div>
</template>

<script>

export default {
  data() {
    return {
      chartOptions: {
        series: [{

           type: 'pie',
           name: 'Browser share',
           data: [
              ['Firefox',   45.0],
              ['IE',       76.8],
              ['Safari',    8.5],
              ['Opera',     6.2],
              ['Others',   0.7]
           ]
        }],

      }
    };
  }
};
</script>

Being new to Vue, I'm unsure where to execute the API request in this setup. While I have seen examples utilizing axios for API calls and data presentation, my scenario requires the data to be within the component for the chart to function properly. Should I make the API call directly from the component? Or am I overlooking something essential?

Answer №1

To handle loading data in your application, first define the variable but initialize it as null:

series: [{
   type: 'pie',
   name: 'Browser share',
   data: null
}],

In the created hook (marked as async for async/await pattern), use axios to fetch and load the data:

import axios from 'axios';
export default {
  data() {
  ...
  },
  async created() {
    const response = await axios.get(...);  // Fetch data from your API endpoint
    this.chartOptions.series[0].data = response.data;  // Assign retrieved data to the chart
    // `response.data` should include:
    /*
      [
        ['Firefox',   45.0],
        ['IE',       76.8],
        ['Safari',    8.5],
        ['Opera',     6.2],
        ['Others',   0.7]
      ]
    */
  }
}

Check out this sandbox example that simulates this process using a setTimeout

Answer №2

import axios from 'axios';

 data () {
  return {
    fetchedData: []
  }
  },
  methods: {
    fetchData() {
        axios.get('https://127.0.0.1:8000/user/getdata')
      .then((result) => {
        this.fetchedData = result.data;
      })
    }
  },
  mounted() {
  this.fetchData();
  }
})

If you want to display it in html, then you make a loop.

<div v-for="dataItem in fetchedData" :key="dataItem.id">
{{dataItem}}
</div>

Answer №3

If you need data to load in your new component, simply create a function within the component. For example, if you are working with a chart component, you can use Axios to make a request for the necessary data. Here is an example of how the script section might appear:

<script>
import axios from 'axios';

    export default {
      data () {
        return {
          graph_data: [],
        }
      },
      created () {
        this.fetchGraphData()
      },

      methods: {
        fetchGraphData() {
           axios.get('your_address')
             .then(function (response) {
               //Fill your data here
             })
        }
     }
</script>

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

Error code 403 is returned when attempting to send an ajax Post request, indicating

While my code runs smoothly on localhost using a WAMP server, I encountered a 403 (forbidden) error after transferring it to a shared hosting environment. My first attempt was: $.post('login.php?login', { user_email: user_email, user_password: u ...

Enhancing middleware chaining in Express

Below is the code for my Express configuration: var server = express() .use(express.cookieParser()) .use(express.session({secret: buffer.toString('hex')})) .use(express.bodyParser()) .use(express.static('./../')); serv ...

Tips on viewing class object values within the `useEffect` hook

App.js import React, { useRef, useEffect } from "react"; import Token from "./Token"; export default function App() { const tokenRef = useRef(new Token()); useEffect(() => { console.log("current index of token: ", ...

Utilizing the 'container' property in a React.js React-Bootstrap modal

How can I open a modal within a designated container using the native property "container"? Whenever I specify the class name of the container element, I encounter an error TypeError: Cannot use 'in' operator to search for 'current' in ...

Using Node.js to send a response only after every promise has been resolved

I am currently working on a NodeJS Express route where I have encountered an issue. In this route, a function is called multiple times, each returning a Promise. The values from these Promises are then added to an Array and sent back to the client using re ...

Tips for identifying and swapping values/parameters in a URL during redirect

To provide more clarity on my inquiry, I will outline the details below: There are three links: Link A, Link B, and Link C Link A: {c_val} Link B: {id} Link C: In the database, there is a value adgaf7g6adf6gadfg8a86fgs9f6g The main focus here is when ...

Uncovering data from a dynamic website through the combination of Selenium and PhantomJS

I am attempting to obtain the timer value from this website http://prntscr.com/kcbwd8 located at , and ideally save it in a variable. import urllib from bs4 import BeautifulSoup as bs import time import requests from selenium import webdriver from urllib. ...

parsing and building a sophisticated JSON object

i have a complex array structure as shown below, array=[ { 'mm': '1', exp: 'exp1' }, { 'mm': '2', exp: 'exp2' }, { 'mm': [ '1', '3', '7' ], exp: &ap ...

Encountering an error while testing a Vue component with v-dialog in Vitest: TypeError - globalStack.at is not a function

I've set up a vue project with vuetify and vitest. When running unit tests using happy-dom (also tried jsdom), everything works fine unless my component contains a v-dialog component, in which case I encounter the following error: TypeError: globalSta ...

The package.json file engines field specifying the version with a tilde and then a greater than sign (~>)

When a package.json file includes an engines field such as this: "engines" : { "node" : "~>12" }, What is the significance of ~> in this context? ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

"Encountering a 404 error in a JQuery Ajax POST request when trying to send

Recently, I have been working with Adobe InDesign extensions and one of the tasks involves uploading an XML file to a server using a jQuery AJAX POST call. To achieve this, I need to read the XML file from the file system, store it in a variable, and then ...

Displaying the second div once the first div has loaded, then concealing the first div

Current Approach: There are two divs occupying the same space, with div1 set to display:block and div2 set to display:none When a tab is clicked, jQuery hides one div over a period of 2000ms and reveals the other div. Challenge: The goal is for the ...

The Vue Multiselect feature lacks accessibility for screen readers when in a disabled state

My current project involves using Vue and multiselect to create a dropdown menu of countries. I have encountered an issue where the dropdown is preselected with a value and disabled. Despite this, I need the selected value to remain accessible for screen r ...

Delay the v-alert display after an item is added to the array basket using setTimeout

here is my custom rightTableMenu template <template> <div> <h1 align="center">{{ title }}</h1> <v-alert type="info" icon="mdi-emoticon-sad" v-if="basketStatus"> Empty Basket, please add some to basket < ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Encountering an "Unmet Peer Dependency" error message while attempting to integrate bootstrap-ui into my Angular project

Currently, my goal is to successfully install angular-ui. Following the tutorials, I have attempted all commands such as: npm install angular-bootstrap However, this command results in an error message: +-- UNMET PEER DEPENDENCY angular@>=1.5 After ...

The Javascript executor in Selenium is delivering a null value

My JavaScript code is causing some issues when executed with Selenium's JavascriptExecutor. Strangely, the code returns null through Selenium but a value in Firefox developer console. function temp(){ var attribute = jQuery(jQuery("[name='q& ...

Unable to pass the jQuery value - troubleshooting tips for Laravel

JavaScript Issue return response()->json([ 'category' => $category, 'editRoute' => $artistCategoriesEditRoute ]); AJAX Response category Object { id: 1, title: "tt", parent_id: 0, … } id ...

The error handler in AngularJS $http service is always left wanting for a call

Here's the code snippet I'm currently using: $http .post('/api/login', $scope.user) .success(function (data, status, headers, config) { // code }) .error(function (data, status, headers, config) { // code }); It seems to be functi ...