Stimulus Discourse

Determine if controller has been disconnected


#1

I haven’t exactly run into this scenario just yet but was thinking about while writing a controller:

export default class extends Controller {
  public connected() {
    fetch("/whatever").
      then((response) => response.text()).
      then((text) => {
        // Do something with this.element
      });
  }
}

For setTimeout or setInterval, I can cancel the timeout or the interval in the disconnect callback. But for fetch, are we expected to cancel the fetch in the disconnect callback as well? I’m not entirely sure how to do that (using what-wg), but beyond this example, are there situations where you’re in a async callback that is after this.element is disconnected? If that’s the case, would it be helpful to have a variable/method to call to get the state of the controller (whether it’s connected or disconnected)?


#2

Aborting fetch requests:


#3

FWIW, you don’t have to cancel the request if the controller disconnects. It still has a reference to this.element and will complete without error.


#4

Thanks for the info @javan… aborting fetch seems painful. In any case, I’m totally fine with letting the fetch happen since there’s still a reference this.element. In my specific case though, I’m doing a full replacement on this.element, so I have to make sure it hasn’t been removed from the DOM (this.element.parentNode != null). I guess this little gotcha is just something someone using Stimulus just has to understand and plan for accordingly.