Skip to content

Instantly share code, notes, and snippets.

@adamori
Created November 12, 2023 14:19
Show Gist options
  • Save adamori/35cbc501c14e71db430b2f396299587d to your computer and use it in GitHub Desktop.
Save adamori/35cbc501c14e71db430b2f396299587d to your computer and use it in GitHub Desktop.
Extension of the Axios library for use with Vue.js. The main purpose is to integrate a loading indicator (using Vue's Ref type) with Axios requests to automatically change state of loading state.

Axios Loading State Reactivity

Extension of the Axios library for use with Vue.js. The main purpose is to integrate a loading indicator (using Vue's Ref type) with Axios requests to automatically change state of loading state.

Check the example project

Steps

  1. Create or insert into existing env.d.ts file located on the same directory with tsconfig.json. If you don't use typescript in your project, skip
import 'axios';
import type { Ref } from 'vue';

declare module 'axios' {
  interface AxiosRequestConfig {
    isLoading?: Ref<boolean>;
  }
}
  1. Create file to initialize instance of axios. In my case it is utils.ts
import axios from 'axios'

const instance = axios.create({});

const updateLoadingStatus = (config: any, status: boolean) => {
  if (config.isLoading)
    config.isLoading.value = status
};

instance.interceptors.request.use((config) => {
  updateLoadingStatus(config, true);
  return config;
});

instance.interceptors.response.use(
  (response) => {
    updateLoadingStatus(response.config, false);
    return response;
  },
  (error) => {
    if (error.response) {
      updateLoadingStatus(error.response.config, false);
    } else if (error.config) {
      updateLoadingStatus(error.config, false);
    }
    return Promise.reject(error);
  }
);

export default instance as typeof axios;
  1. Use axios and include reactive variable when requesting. Look at the example:
<script lang="ts" setup>
import {ref} from "vue";
import axios from "./utils";

const isLoading = ref(false);

function get() {
  axios.get("https://jsonplaceholder.typicode.com/todos/1", {
    isLoading: isLoading
  }).then(async (response) => {
    console.log(response.data);
  }).catch((error) => {
    console.log(error);
  });
}

</script>

<template>
  <header>
    <h1>Axios Reactivity Example</h1>
  </header>

  <main>
    <button @click="get" :disabled="isLoading">Get</button>
  </main>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment