AJAX Axios loading JavaScript

0

I am doing an AJAX request using the Github API by the axios and wanted to know how I do for while loading the information, it gives a console.log('carregando'); and create a component written "loading", and after that it deletes the loading messages.

This is my current code:

axios.get('https:api.github.com/users/marceloh13')
    .then(function(response){
        console.log(response);
        console.log(response.data.avatar_url)
    })
    .catch(function(error){
        console.log(error);
    });
    
asked by anonymous 05.09.2018 / 22:07

2 answers

1

Just run console.log before making the same AJAX request. And then just take advantage that the axios returns a Promise and add a .then at the end to "cancel" the "loader".

console.log('Carregando...');
axios.get('https:api.github.com/users/marceloh13')
    .then(function(response){
        console.log(response);
        console.log(response.data.avatar_url)
    })
    .catch(function(error){
        console.log(error);
    })
    .then(function(response){
        console.log("AJAX finalizado"); // sempre executa
    });

Edit : Adding a functional example .

    
05.09.2018 / 22:21
1

You can find the answer in the Axios documentation itself. Use Interceptors

link > Interceptors

  

You can intercept requests or responses before they are handled by then or catch.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
  }, function (error) {
// Do something with request error
return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
    
11.09.2018 / 11:04