简体   繁体   中英

await api call responding after unmounting of component | vue.js

I have an method(doSomething) which will be called on mounted state and also have a CTA to unmount the component. Before the await call finish if user unmount the component with back CTA, the controller is still coming back to unmounted component. How to abort the response coming back to the component.

Vue Component:

doSomething(){
   let data = await someApiCall();
   console.log(data)
}

Store.js(vuex)

someApiCall(){
  axios.get("apicall").then(res => res);
}

Instead of abandoning, you could stop the 'unmount CTA' being clickable in the first place - until the doSomething() method has been completed its fetch.

export default {
  data() {
      return {
          isFetching: false,
      }
  },
  methods: {
      async doSomething() {
          this.isFetching = true
          let data = await someApiCall()
      },
      myUnmount() {
          // Do your unmount
      },
  },  
  async mounted(){
      await this.doSomething()
      this.isFetching = false
  }
}

And then bind this to the CTA;

<button @click="myUnmount()" :disabled="isFetching">Unmount</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM