I have a class that manages access to a football API. The class has a field called season
which represents the current season of play as a string. Tu update this I have a method to re-assign the season
-field, which is my getCurrentSeason()
-method.
I need access to season
, but would also like to set the value of season
in the constructor to have a value as soon as I initialize my ApiManager
. I saw it was possible to call this.getCurrentSeason()
from a similar piece of code, but season
remains an empty string in my case.
Through debugging, I can see that the API call comes through and gives access to the necessary information. I was thinking of just returning the season in getCurrentSeason()
so I could call this.season = getCurrentSeason()
in the constructor instead, but I would still like to be able to call the method elsewhere to update the fields of my ApiManager
, so I would like to avoid this approach.
Code below. Any help is appreciated.
import fetch from 'node-fetch';
export class ApiManager {
constructor() {
this.season = '';
this.options = {
method: 'GET',
headers: {
... // API key removed
}
};
this.getCurrentSeason();
}
async getCurrentSeason() {
const url = 'https://api-football-v1.p.rapidapi.com/v3/leagues?id=39¤t=true';
try {
let response = await fetch(url, this.options);
let json = await response.json();
this.season = json['response'][0]['seasons'][0]['year'];
} catch (error) {
console.log("Error: " + error);
}
}
}