AJAX Javascript loading message axios

Asked

Viewed 1,198 times

0

I’m making an AJAX request using the Github API from Axios and wanted to know how I do to, while uploading the information, it give 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);
    });

2 answers

1

Just run the 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 "Download".

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.

  • however later I wanted to change this console.log to a <H1> written "loading" and after it loads the <H1> some, that way n would work.

  • On the contrary. Just replace the first console.log for ajaxFeedback.hidden = false; and the console.log of the latter then for ajaxFeedback.hidden = true. In this case it would be necessary that ajaxFeedback is already assigned.

  • I added a Jsfiddle with a working example to give you an idea.

  • Fernando, I don’t understand how I create a <H1> component like this.

  • If you want to create one <h1> each time a request is started would have to use document.createElement('h1') and then add to the DOM with appendChild or insertBefore. But this is not at all performatic, so I just show and hide the element. But the point is not this, with the code shown already gives to have notion of where to put your codes to give feedback to user.

1

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

https://github.com/axios/axios > 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);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.