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

Activate automatic selection when the input field is disabled

How can I enable auto-select for text in an input field even when it is disabled? Currently, the auto select feature doesn't work when the field is disabled. Here is my HTML: <input type="text" class="form-control" ng-model="gameId" select-on-cli ...

What is the best way to align a TabPanel component at the center using React Material UI

As I attempt to compile a list of articles while switching to a list of other entities in React + material UI, I have encountered some difficulties. Specifically, I am struggling to center the Card displaying an article in alignment with the centered Tabs. ...

The appearance of an unforeseen * symbol caused a

Having issues with this particular line of code, import * as posenet from '@tensorflow-models/posenet' The error 'Uncaught SyntaxError: Unexpected token *' keeps popping up, I have the latest version of Chrome installed and I've ...

Ensure the item chosen is displayed on a single line, not two

I've encountered an issue with my select menu. When I click on it, the options are displayed in a single line. However, upon selecting an item, it appears on two lines - one for the text and another for the icon. How can I ensure that the selection re ...

Removing background color and opacity with JavaScript

Is there a way to eliminate the background-color and opacity attributes using JavaScript exclusively (without relying on jQuery)? I attempted the following: document.getElementById('darkOverlay').style.removeProperty("background-color"); docume ...

Dividing the code into a function and invoking it does not produce the desired outcome

Everything seemed to be working perfectly until I attempted to encapsulate the code into a function and call it within my expression. Unfortunately, this approach did not yield the desired results. Functional code: render: function() { return ( ...

Having trouble with PHP's $_GET not reading my AJAX URL accurately

It seems like there might be an issue with how the $_GET variable is interpreting my ajax URL, possibly due to a deep linking plugin I have installed. The final URL that is causing trouble looks like this: /dashboard.php#/projectSetup.php?mode=edit&ge ...

The props in Vue 3 are not functioning as expected in child components even after being bound correctly, resulting in undefined values in the child component

Exploring the realms of Vue and Laravel, I find myself in new territory. As the parent element, I fetch items from the database successfully. Now, the task at hand is to pass this data to the child component. <template> <div class="todoList ...

What are the distinct roles of the server and client in a Nuxt SSR application?

Currently, I am working with Nuxt 2.13 and developing an e-commerce platform. However, I have encountered some server resource issues where the initial site load is taking longer than expected (although route changes are fast and smooth). I am curious to ...

The socket.rooms value is updated before the disconnection listener finishes its process

When dealing with the "disconnect" listener, it's known that access to socket.rooms is restricted. However, I encountered an issue with my "disconnecting" listener. After making some modifications to my database within this callback, I attempted to em ...

What is the significance of using parentheses around a function in JavaScript?

Currently, I am developing an application using Java and JavaScript, and while reviewing some code today, I came across a segment that seemed confusing to me. var myVariable = (function(configObj){ var width = configObj.width; var height = config ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

`In nativescript-vue, data not appearing in first tab on Tabview component`

Within my component, I have implemented a Tabview with 2 tabs. The first tab is used to load data from an API and display it in a ListView, while the second tab shows different data. However, there seems to be an issue where the data from the API does not ...

Newbie Inquiry Renewed: What is the best way to convert this into a functional hyperlink that maintains the data received from the ID tag?

I have no prior training etc. If you are not willing to help, please refrain from responding as I am simply trying to learn here. <a id="player-web-Link">View in Depth Stats</a> This code snippet loads the following image: https://i.stack.i ...

Having trouble getting my Node.js Express code to display 'Hello World' on Cloud 9 platform

Recently, I've been experimenting with Cloud 9 and have been encountering an issue while trying to execute the sample code provided on the Express website to display 'Hello World!'. I have attempted listening on various ports/IP addresses ba ...

Encoding a string in JSON that contains the "#" symbol along with other special characters

The client side javascript code I have is as follows: <html> <script type="text/javascript" src="js/jquery.min.js"></script> <script> $(document).ready(function() { //var parameters = "a=" + JSON.stringify( ...

Tips on specifying a default value when receiving data from an API

I am working with a dropdown list that is populated from an API call. Here is my code snippet: <label>User Code:</label> <select ng-options="c as c.User for c in userList" ng-model="selectedUser" id="search3"> </select> To fet ...

Easy steps to automatically disable a checkbox once the expiration date has been reached

I have this PHP code that retrieves values from my database. I want to prevent users from selecting or modifying items with expired dates. Could you assist me with this? The code below currently displays 'Expired' and 'Not Expired' on ...

The battle between HTML5's async attribute and JS's async property

What sets apart the Html5 async attribute from the JS async property? <script src="http://www.google-analytics.com/ga.js" async> versus (function() { var ga = document.createElement('script'); ga.type = 'text/javascript&apo ...

Creating numerous bar graphs for each specific date

I have a dataset containing dates and corresponding information for each element. Despite trying various approaches, I am unable to create a barchart. Every solution I've attempted has been unsuccessful thus far. The dataset is structured as follows ...