Requesting Axios.get for the value of years on end

I'm grappling with obtaining a JSON file from the server. The endpoint requires a year parameter, which needs to be set as the current year number as its value (e.g., ?year=2019). Furthermore, I need to fetch data for the previous and upcoming years as well. However, hardcoding the years isn't a viable solution since it will require constant manual updates.

Even though my current setup is pretty basic, I've experimented with various approaches that haven't yielded the desired results.

data() {
 return {
  year:[]
 }
},

computed: {
 axiosParams(){
  const params = new URLSearchParams();
  params.append('year', this.year);
  return params;
 }
},

getYears: function() {
    axios.get('myurl',{
     params : this.axiosParams
    }
    }).then((response) => {
      this.year = response.data;
    })
}

When I hardcoded the year by setting it as '2019' in the data section, everything functioned correctly. As a newcomer to Vue and Axios, I'd greatly appreciate any assistance you can provide.

Answer №1

If you want to retrieve the current year or an array of specific years using some javascript magic, you can do so by following this example:

  getYear() {
      var currentDate = new Date()
      var currentYear = currentDate.getFullYear()

      return currentYear
    },

This function will output 2019

  getYears() {
      var yearsArray = []
      var currentDate = new Date()
      for (let i = -1; i < 2; i++) {
        var currentYear = currentDate.getFullYear() + i
        yearsArray.push(currentYear)
      }
      return yearsArray
    },

This function will output an array like this: [2018, 2019, 2020]

You can then decide how you want to utilize this information, whether it's sending just the current year or an array of years to your api.

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

Installing libraries using npm can be done in two ways: using the command `npm install`

While working, we encountered an issue where the icon for the menu block from the rc-menu library was not displaying. Every time we run mvn install We also run npm install In our package.json file, we had included this library "rc-menu":"^5.1 ...

The code functions perfectly in the Adobe Dreamweaver Preview, but unfortunately, it is not compatible with Chrome

In the process of creating a website using Adobe Dreamweaver over the past few days, I encountered an issue with JavaScript that should activate upon scrolling. Interestingly, the script works perfectly fine when accessed through this link (), but fails t ...

How can I simulate mouse position in a UIWebView?

Can the mouse position (x,y) for HTML-5 elements on a UIWebView be programmatically set using stringByExecutingJavascript in order to trigger hover, mouse over, and other interactions? ...

Tips for utilizing props in a Vue component

When trying to incorporate a prop into a computed value, I encounter the following error: [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in ---> at src/cmps/space-details/space-imgs.vue at src/pa ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

Ways to refresh the DOM while making an asynchronous request

Consider the following async function: async function predict_from_model() { $("#loading").html("first update") const model = await tf.loadModel('model.json'); $("#loading").html("second update") //delayed for (var i = 0; i < 100; i++ ...

Finding the right way to cancel a Firestore stream within a Vue component using the onInvalidate callback

Currently, I am utilizing Vue 3 to develop a Firebase composable that is responsible for subscribing to an onSnapshot() stream. I have been attempting to unsubscribe from this stream by invoking the returned unsubscribe() function within both watchEffect ...

What are the steps to successfully integrate Vuetify 2.3 or any other packages into a Vue 3 Project?

How can I properly register Vuetify in my main.js file without using Vue alias? After importing Vuetify, all of my components are hidden. Dependencies: "vue": "^3.0.0-rc.7", "vue-router": "^4.0.0-0", &quo ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

How can I remove the ID of the object data from the list?

When sending the data initially, there are no issues. However, when attempting to update, I am able to delete the root object's id but struggling to delete the ids of objects in the list. Any suggestions on what I can do? const handleSubmit = async ...

Retrieve the red, green, and blue components of a color in the RGB format

When I retrieve "rgb(18, 115, 224)" from a DOM element, I need to convert this color to hexadecimal in order to assign it to a span element. To get the hexadecimal equivalent of the color, I can use the following code snippet: "#" + componentToHex(r) + co ...

Using express.js to send multiple post requests to the same url

My website features a login form where users input their information. Upon submission, a post request is made to check the validity of the provided information. If successful, users are redirected back to the login form where they must enter the code sent ...

What is the best way to integrate PHP code into my countdown JavaScript code to automatically insert data into a MySQL column once the countdown has reached

I have created a countdown JavaScript code that resets every day at 23:00 of local time. I am wondering if it is possible to incorporate PHP code into this script so that after the countdown finishes each day, it automatically adds "5" to my "Credit" col ...

I'm encountering a typescript error as I migrate a Paho MQTT function from Angular 1 to Angular 2 - what could be causing this issue?

When connecting to my MQTT broker, I am working on several tasks. In my Ionic 2 and Angular 2 application, I have created an MQTT provider. Here is the provider code: import { Component } from '@angular/core'; import { NavController, ViewControl ...

Troubleshooting: Issue with dynamically updating innerHTML of element using AJAX in response to selection input change event

I'm facing a challenge in retrieving the value of a product from a database based on user selection in a <select> element and displaying this value using AJAX in another element. When I directly access precio.php?q=PRODUCTO%201, it returns the d ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

The sequence of error middleware in Express4

Encountered a series of code execution that seemed unusual. Here's the code snippet: server.js const Actions_Single_PVC = require('./routes/Actions_single_PVC.js'); app.use('/Actions_single_PVC', Actions_Single_PVC); app.use((e ...

Using the $lookup aggregation stage to $group a nested array in MongoDB

I'm working with a Product Schema that is partially built using mongoose. Here's a snippet: attributes: [ { set: { ref: 'AttributeSet', type: Schema.Types.ObjectId }, items: [ ...

Unable to decipher the mysterious map of nothingness

I am currently working on a GET method in Node.js. My goal is to fetch data using the GET request and then use the MAP function to gather all the names into an array. However, I encountered the following error: /root/server.js:21 ...

What is the best way to display the tabcontent when clicking on a menu tab in this code, as neither method seems to work?

Take a look at my JSFiddle demo: <http://jsfiddle.net/xrtk9enc/2/> I suspect that the issue lies within the javascript section. My html code includes an Unordered List that serves as the tab menu. Each href of the menu corresponds to a tab content, ...