elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

AbortController not working #126

Closed nmocruz closed 2 years ago

nmocruz commented 2 years ago

I have an api client not working and seems that it was working long time ago. not sure if was webpack breaking it or what. some speudocode

class api{
  let controller = null;
  async callMultipletimesUseOnlyLastClicked (a){
      if(this.controller)
           this.controller.abort();
      this.controller = new AbortController();
      let data = await apibase.url('xx').signal(this.controller)
               .get()
               .json()
      controller = null;
      return data;
  }
}

the request can take 2 or 4 sec and to discard the previous requests I'm aborting any controller. before I was able to abort requests but now I have bug here and It seems like a new factory is created and loosing the reference to the controller.

elbywan commented 2 years ago

Hey @nmocruz,

before I was able to abort requests but now I have bug here and It seems like a new factory is created and loosing the reference to the controller.

I'm not sure your issue is related to wretch, I tried reproducing with the code you provided but it seems to be working as expected:

class Api {
  constructor() {
    this.apibase = wretch("https://jsonplaceholder.typicode.com")
  }

  async getPosts () {
    if(this.controller) {
      this.controller.abort()
      console.log("aborted")
    }
    this.controller = new AbortController()
    let data = await this.apibase.url('/posts/1')
      .signal(this.controller)
      .get()
      .json()
    this.controller = null
    return data
  }
}

const api = new Api()

api.getPosts().then(data => console.log("First request", data)).catch(console.error)
api.getPosts().then(data => console.log("Second request", data)).catch(console.error)
Capture d’écran 2022-03-03 à 09 55 52
nmocruz commented 2 years ago

not sure if this is due the way that webpack babel or ts-loader is importing the library because it was working before and stopped after migrating a few libraries like webpack, typescript etc. I did a bit of debugging and seems like is called selfFactory a few times and the last is losing the reference to the controller. I can be wrong because my webpack source maps are not perfect.

elbywan commented 2 years ago

I did a bit of debugging and seems like is called selfFactory a few times and the last is losing the reference to the controller. I can be wrong because my webpack source maps are not perfect.

Hmm this is weird, selfFactory preserves fetch options (signal is an option) unless specified otherwise explicitely by calling .options(…, true).

I don't think that this issue is related to wretch itself so I'm going to close it. Feel free to reopen if you can provide a reproducible sample.