-1

Putting Json data in a this.variable but I keep getting the error Uncaught (in promise) TypeError: Cannot set property 'weather' of undefined. Does anyone know how to fix this.

var currentWeather;

function setup() {
  createCanvas(400, 400);
  currentWeather = new CurrentWeather();
  currentWeather.create();
  loadJSON(currentWeather.api, currentWeather.gotData);
}



function draw() {
  background(0);
}

///////////////////////////////////////////////////////////////////

class CurrentWeather{

 create(){
  let url =       'https://api.openweathermap.org/data/2.5/weather?q=';
  let city = 'Manassas';
  let apiKey ='ApiKeyHere';
  let units = '&units=imperial';
  this.api = url + city + apiKey + units;
   this.weather;
 }

 gotData(data){
   this.weather = data;
 }

}
jhpratt
  • 6,841
  • 16
  • 40
  • 50
BeanieGod
  • 61
  • 1
  • 1
  • 2

1 Answers1

0

Try to change this line loadJSON(currentWeather.api, currentWeather.gotData); to

loadJSON(currentWeather.api, currentWeather.gotData.bind(currentWeather));

You are having scoping issues. this is being overridden/lost from your callback methods. In your case this supposed to be the instance of CurrentWeather which you have as currentWeather = new CurrentWeather();. .bind(currentWeather) is used to scope this to a specific function. Also since the currentWeather is defined globally you may need to just use that variable instead of using this in some cases. It's hard to tell where other issues are without the full code.

Kubwimana Adrien
  • 2,463
  • 2
  • 8
  • 11