Search code examples
vue.jstimeoutaxiosinterceptormount

Create component on the fly with custom data


First of all, I’m not a vue expert, so i’m sorry if i missunderstand anything

In my app I need to implement the following: Every request that has a timeout should show a popup where the user would be able to resend the request. For this, I’m using axios, and I have created an interceptor for catch the timeout request

export const authenticated = Axios.create({
  timeout: 100,
})

authenticated.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.code === 'ECONNABORTED') {
      //create and show popup
      var ComponentClass = Vue.extend(TimeoutModalDialog)
      var instance = new ComponentClass()
      instance.$mount('#page')
    }
    return Promise.reject(error)
  }
)

Here I have all the data of the request in ‘error.config’ so what I want is to send this object to the new component (TimeoutModalDialog). I would like to know also if there is a better way to create and show dynamic vue components.

I hope you can help me Best regards


Solution

  • At the end I have implemented this to solve my problem:

    authenticated.interceptors.response.use(
      response => {
        return response
      },
      error => {
        if (error.code === 'ECONNABORTED') {
          return new Promise((resolve, reject) => {
            var modalDialogId = "timeout-modal-dialog";
            if($('#' + modalDialogId).length){
              instance.$children[0].loadingComplete = true;
            } else {
              var ComponentClass = Vue.extend(TimeoutModalDialog);
              instance = new ComponentClass({
                propsData: {
                  retryFunction: function () {
                    instance.$children[0].loadingComplete = false;
                    authenticated.request(error.config).then((response) => {
                      instance.$children[0].loadingComplete = true;
                      $("#" + modalDialogId).modal("close");
                      resolve(response);
                    }, (error) => {
                      instance.$children[0].loadingComplete = true;
                      reject(error);
                    })
                  },
                  cancelFunction: function () {
                    instance.$children[0].loadingComplete = true;
                    $("#" + modalDialogId).modal("close");
                    reject(error);
                  },
                  dialogId: modalDialogId
                }
              });
              instance.$mount();
              document.getElementById('modalVueGeneric').appendChild(instance.$el);
            }
          });
        } else {
          return Promise.reject(error);
        }
      }
    );
    

    And it solves my problem.

    Thanks Laran for your suggestion.