Use fetch In A JavaScript Class
export class Widget {
constructor() {
this._data = null;
this.init().then(({data}) => {
this._data = data;
this.ping();
})
}
ping() {
console.log(this._data);
}
async init() {
const response = await fetch('/data/stations.json');
if (!response.ok) {
throw new Error('There was a problem getting the data')
};
const data = await response.json();
return { data }
}
}
This is how I'm loading data in a JavaScript class on init so that it's ready before you do anything else with the class. The ping()
method is where I'd do stuff like adding buttons to the page that interact with the class.