Stimulus Discourse

Handbook External Resources example with fetch and this


#1

I’m following the handbook example https://stimulusjs.org/handbook/working-with-external-resources and this is undefined in the response.

My actual code is below. I don’t see how it is different from this.element.innerHTML = html in the handbook example.

connect() {
  this.updateStatus()
}

updateStatus() {
  fetch(this.data.get("url"))
    .then(response => response.json())
    .then(status => {
      this.element.classList.add(status["duty_status"]) // `this` is undefined here
  })

}

Thanks for the help/suggestions.


#2

Hmm, your code looks fine to me. What kind of build tooling are you using to compile your JavaScript?

I made an example using https://github.com/stimulusjs/stimulus-starter and it works as expected: controllers/json_loader_controller.js :point_right: https://brief-plot.glitch.me/