f3oall / awesome-notifications

Lightweight JavaScript Notifications Library
https://f3oall.github.io/awesome-notifications/
MIT License
286 stars 40 forks source link

Axios interceptors and async loading #7

Closed n-osennij closed 5 years ago

n-osennij commented 5 years ago

I use vue.js with axios library to send requests to my API. I want configurate it globaly and show Loading message, if request is too long.

I found, that I can use axios interceptors to configure axios globaly

axios.interceptors.request.use((config) => {
    // Do something before request is sent
    return config;
  }, (error) => {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use((response) => {
    // Do something with response data
    return response;
  }, (error) => {
    // Do something with response error
    return Promise.reject(error);
  });

To show notifications I use this package - awesome-notifications

axios.interceptors.request.use((config) => {
    this.$awn.info("Try to send request");
    return config;
}, (error) => axios_error(error));

axios.interceptors.response.use((response) => {
    this.$awn.success("Success!");
    return response.data;
}, (error) => axios_error(error));

function axios_error(error) {
    //this.$awn.alert("Request error"); // not works - Uncaught (in promise) TypeError: Cannot read property '$awn' of undefined

    return Promise.reject(error);
}

But I have next problem:

I don't want to show success messages using sucess method. I want to use asyncBlock() method - it shows loader and blocks the screen untill promise will be completed, then run a callback or show new toast.

asyncBlock(promise, onResolve, onReject, html)

But how can I use it inside interceptors.request and interceptors.response?

I just want globaly configure next behavior: if I send requst and it's duration more than 500ms - show asyncBlock dots (fullwindow loading message). If an error occurred during the request, show error message - this.$awn.alert("Request error"). If no errors - don't show any messages.

How can I do this? Any other variants?

darksectordds commented 5 years ago

You can use something like that:

this.$awn.async(axios.post('/dashboard/categories/transfer', {
    from: this.categoryFrom.id,
    to: this.categoryTo.id
}).then((response) => {
    return this.$awn.success(response.data.message);
}).catch((error) => {
    return this.$awn.alert(error.response.data.message);
}));
f3oall commented 5 years ago

Closed due time passed. If you still need assist, please create new issue. Make sure that you familiar with 3.0.0 version before doing this.