Search code examples
javascriptarraysvue.jsgetaxios

Axios.get call for years as value


I am trying to get a json file from server. Endpoint has a year parameter with the current year number as value like so: ?year=2019. I also need to get a year before that and next year. So if someone enters data in the backend for 2018, 2019 or 2020 I should be able to retrieve it. The problem is that I cannot hard code the years since next year I would need 2019, 2020 and 2021 and so on :)

I currently have pretty basic setup but have tried all sorts of things which of course don't work.

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;
    })
}

If I hardcode it like year: '2019' in the data, everything works ok. I am new to Vue and Axios so any help would be greatly appreciated.


Solution

  • You could just use a little javascript magic to get this year or an array of the years you want like so:

      year() {
          var now = new Date()
          var nowy = now.getFullYear()
    
          return nowy
        },
    

    This will return 2019

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

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

    Then it's up to how you use that, you can send either this year or an array to your api.