Menu Close

How to show loading when making ajax request with Axios in Vue.js?

Sometimes, we want to show loading when making ajax request with Axios in Vue.js.

In this article, we’ll look at how to show loading when making ajax request with Axios in Vue.js.

How to show loading when making ajax request with Axios in Vue.js?

To show loading when making ajax request with Axios in Vue.js, we can add Axios request and response interceptors and set the loading state in the interceptor methods.

For instance, we write

<script>
//...
export default {
  //...
  created() {
    axios.interceptors.request.use(
      (config) => {
        this.isLoading = true;
        return config;
      },
      (error) => {
        this.isLoading = false;
        return Promise.reject(error);
      }
    );

    axios.interceptors.response.use(
      (response) => {
        this.isLoading = false;
        return response;
      },
      (error) => {
        this.isLoading = false;
        return Promise.reject(error);
      }
    );
  },
  //...
};
</script>

to call axios.interceptors.request.use to add a request interceptor and call axios.interceptors.response.use to add a response interceptor in the component’s created hook to add the interceptors before the component is mounted.

We call them with methods that sets isLoading to differnt values.

We have this.isLoading = true; when we’re making the request

And in the other functions, we set isLoading to false since the request is finished.

Conclusion

To show loading when making ajax request with Axios in Vue.js, we can add Axios request and response interceptors and set the loading state in the interceptor methods.

Posted in vue