request.ts 768 B

1234567891011121314151617181920212223242526
  1. import { ref, UnwrapRef } from 'vue';
  2. import { AxiosResponse } from 'axios';
  3. import { HttpResponse } from '@/api/interceptor';
  4. import useLoading from './loading';
  5. // use to fetch list
  6. // Don't use async function. It doesn't work in async function.
  7. // Use the bind function to add parameters
  8. // example: useRequest(api.bind(null, {}))
  9. export default function useRequest<T>(
  10. api: () => Promise<AxiosResponse<HttpResponse>>,
  11. defaultValue = [] as unknown as T,
  12. isLoading = true
  13. ) {
  14. const { loading, setLoading } = useLoading(isLoading);
  15. const response = ref<T>(defaultValue);
  16. api()
  17. .then((res) => {
  18. response.value = res.data as unknown as UnwrapRef<T>;
  19. })
  20. .finally(() => {
  21. setLoading(false);
  22. });
  23. return { loading, response };
  24. }