I keep fetching data from the server using my vue.js code

Vue.js is new to me and I'm still trying to grasp its concepts (please ignore the indentation in the code)


methods:{
getdata() {
  if (this.myPage.month === 5) {
    axios.get("http://www.amock.io/api/maymock").then(response => {
      this.Month = response.data.checkInData.Month;
      this.Stat = response.data.checkInData.CheckedInStat;
      this.TotalTarget = response.data.checkInData.TotalTarget;
      this.$emit("TotTarget", this.TotalTarget);
      this.TargetForMonth = response.data.checkInData.CurrentAchieved;
      this.$emit("TotCount", this.TargetForMonth);
  })
}
if (this.myPage.month === 4) {
axios.get("http://www.amock.io/api/aprilmock").then(response => {
this.Month = response.data.checkInData.Month;
this.Stat = response.data.checkInData.CheckedInStat;
this.TotalTarget = response.data.checkInData.TotalTarget;
this.$emit("TotTarget", this.TotalTarget);
this.TargetForMonth = response.data.checkInData.CurrentAchieved;
this.$emit("TotCount", this.TargetForMonth);
})
}

},
},

computed: {
attributes() {
this.getdata();
let checkindata = [];
if (this.Click === 0) {
var entry = new Object();
(entry.highlight = "red"), (entry.dates = new Date());
checkindata.push(entry);
for (var day = 0; day < this.Stat.length; ++day) {
entry = new Object();
(entry.highlight = this.Stat[day] === 0 ? "red" : "green"),
(entry.dates = new Date(2020, this.Month, day + 1));
checkindata.push(entry);
}
}
if (this.Click === 1) {
var entry1 = new Object();
(entry.highlight = "green"), (entry.dates = new Date());
checkindata.push(entry1);
for (day = 0; day < this.Stat.length; ++day) {
entry1 = new Object();
(entry.highlight = this.Stat[day] === 0 ? "red" : "green"),
(entry.dates = new Date(2020, this.Month, day + 1));
checkindata.push(entry1);
}
}
return checkindata;
}
},

data() {
return {
myPage: {},
Stat: [],
Month: null,
TotalTarget: null,
TargetForMonth: null,
responded: null
};
}

I've integrated a v-calendar plugin and the data is being passed to the Calendar through the attributes function. However, I want the getdata method to fetch data from the provided link only when the variable myPage.month changes, and it should do so just once. The method currently runs infinitely, causing issues. Is there a way to resolve this?

Answer №1

It's not recommended to call getData() within a computed property since it can lead to state mutation and unnecessary recalculations.

A better approach would be to use a watcher instead. Monitor changes in myPage.month and trigger getData() accordingly.

Here's an example:

watch: {
  'myPage.month': {
    immediate: true,
    handler() {
      this.getData();
    }
  }
}

Some additional tips for improvement:

  • Replace new Object() with {}.
  • Split statements like (x = 1), (y = 2) into separate lines with a semicolon instead of a comma.
  • You can construct the object in a single step:
var entry = {
  highlight: "red",
  dates: new Date(),
};
checkindata.push(entry);
  • Minimize duplicated code by optimizing the logic:
getData() {
  let api;
  switch (this.myPage.month) {
    case 4: api = 'aprilmock'; break;
    case 5: api = 'maymock'; break;
    default: return;
  }

  axios.get(`http://www.amock.io/api/${api}`).then(response => {
    this.Month = response.data.checkInData.Month;
    this.Stat = response.data.checkInData.CheckedInStat;
    this.TotalTarget = response.data.checkInData.TotalTarget;
    this.$emit("TotTarget", this.TotalTarget);
    this.TargetForMonth = response.data.checkInData.CurrentAchieved;
    this.$emit("TotCount", this.TargetForMonth);
  });
}

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

Using the moment library in Angular to convert date and time can sometimes lead to errors

Whenever I attempt to convert a Gregorian date to a Persian date, the minute value in the conversion ends up becoming an error. For instance, let's say I want to convert this specific date and time to a Persian date: 2020-09-14T16:51:00+04:30 should ...

Issue encountered when integrating vue2-google-maps into a project using vue.js and Laravel 5.6.12

I am currently utilizing Laravel 5.6.12 in combination with vue.js I am attempting to integrate Google Maps using the following GitHub link I am adhering to the instructions provided in the aforementioned link, as follows. Installation npm install vue2 ...

React - Managing multiple requests using Ajax

Within my react application, there is a Grid feature that allows users to select multiple rows at once and then perform a bulk action on them by clicking a button. Running on the server side, I have a script that needs to be executed for each selected row ...

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...

Why is it that every time I try to execute this function, my table fails to populate as expected?

I'm having trouble creating a table with 2 rows, each row containing 4 cells that should display an image. However, when I try to execute my function, nothing seems to happen. Can you help me troubleshoot? function generateTable() { var table = d ...

When working with Vue 3, remember that inject() function is only allowed within setup or functional components

I'm puzzled as to why I keep encountering this error. I am attempting to utilize the Vuex store in a composition function, but for some reason, it keeps throwing an error regarding inject (even though I'm not using inject at all). My application ...

Retrieving document attributes from a Mongoose Model with the help of Typescript

Incorporating Typescript with Mongoose, my aim is to retrieve properties from a Model. Taking the illustrated UserModel as an example import mongoose, { Schema } from 'mongoose'; const userSchema: Schema = new mongoose.Schema({ _id: mongoos ...

How to eliminate file extensions with grunt-contrib-connect and grunt-connect-rewrite

I'm struggling to find a solution for eliminating the '.html' extension from files within my grunt web app. should display index.html from the respective folder. However, in the absence of a trailing slash (), the page should instead look ...

Encountering an error message stating that navigator.block is not a function when attempting to navigate to

Working on a React project, I have implemented a popup modal that should appear when a user tries to make changes in an input field and navigate to another screen. However, it is not functioning as expected. After researching various online resources, I ha ...

Guide on invoking a function in a PHP file using jQuery's load method

I am having trouble displaying the data retrieved from the database. There is a function called "getComments(page)" in the getComments.php file, where 'page' is an integer parameter corresponding to the chosen database. I need to call this functi ...

Tips for dividing HTML code on a page into individual nodes

I am looking to extract the HTML content from a website and then parse it into nodes. I attempted the following code: function load() { $(document).ready(function () { $.get("https://example.com/index.html", function (data) { const loadpage ...

Angular JS: Automatically toggle the visibility of a div on a panel click event

There is a row, panel, and a closed div on load. Clicking on the panel should make the div appear while making the row and panel disappear. Clicking on X should make the panel and row appear again. <script src="https://ajax.googleapis.com/ajax/libs/ ...

Implement a recursive approach to dynamically generate React components on-the-fly based on a JSON input

My goal is to develop a feature similar to Wix that allows users to drag and drop widgets while adjusting their properties to create unique layouts. To achieve this, I store the widgets as nested JSON documents which I intend to use in dynamically creating ...

Duplicate a Google Sheet and save it to a specific folder in Google Drive

I currently have two spreadsheets in my possession. The first spreadsheet consists of raw data that includes unique employee numbers and the names of the employees. The second spreadsheet is the one I aim to duplicate to a designated Google Drive folder. M ...

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

Can you explain the reference point used in the `drawImage()` function on a canvas?

Here is an inquiry concerning the usage of the drawImage() function. var x = (i-j)*(img[0].height/2) + (ctx.canvas.width/2)-(img[0].width/2); var y = (i+j)*(img[0].height/4); abposx = x + offset_x; abposy = y + offset_y; ctx.drawImage ...

Using Bootstrap 4 beta for Form Validation

I'm struggling to grasp the concept of building validation forms. The bootstrap documentation includes a JS code snippet (referred to as starter code) like the one below: <script> // Example starter JavaScript for disabling form submissions if ...

Guide to designing a bar graph using HTML5 for a web app optimized for iPad

I am in the process of converting my iOS native app for iPad to a web app using HTML5. However, I am encountering an issue with creating a bar graph for the HTML5 app. Is there any documentation or built-in API available for this specific task? On iOS, we ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

Tips on how to reset the default placeholder of the jQuery plugin 'intl-tel-input' programmatically

With the int-tel-input jQuery plugin, resetting the placeholder to default may sometimes be necessary. Is there a method similar to: $('input').intlTelInput('setPlaceholder', 'myDefaultPlaceholder' ); that needs to be called ...