How do I set the class properties of the class below? The latitude and longitude of the class is still undefined after the scope of setLatLong(). I have tried to make variable inside the setLatLong()-function and returned them, but apparently I can't figure out how variables and scopes work in Javascript.
To those who want to try the link, replace this.street_name with 'hvid*' and this.zip_code with '2400'.
import React from "react";
class Place {
street_name;
zip_code;
latitude;
longitude;
constructor(zip_code, street_name, latitude = 0, longitude = 0) {
this.zip_code = zip_code;
this.street_name = street_name;
this.setLatLong(latitude, longitude);
}
setLatLong(latitude, longitude) {
const url = `https://api.dataforsyningen.dk/adgangsadresser?q=${this.street_name}&postnr=${this.zip_code}&struktur=mini`
if (latitude === 0 && longitude === 0) {
fetch(url)
.then(response => response.json())
.then(json => {
let item = json[Math.floor(Math.random() * json.length)];
this.latitude = item.y;
this.longitude = item.x;
})
}
}
}
export default Place;